using Indotalent.Infrastructure.Database;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Indotalent.Features.Sales.DeliveryOrder.Cqrs;

public record DeleteDeliveryOrderByIdCommand(string Id) : IRequest<bool>;

public class DeleteDeliveryOrderByIdHandler : IRequestHandler<DeleteDeliveryOrderByIdCommand, bool>
{
    private readonly AppDbContext _context;
    public DeleteDeliveryOrderByIdHandler(AppDbContext context) => _context = context;

    public async Task<bool> Handle(DeleteDeliveryOrderByIdCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.DeliveryOrder
            .FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken);

        if (entity == null) return false;

        var transactions = await _context.InventoryTransaction
            .Where(x => x.ModuleId == entity.Id && x.ModuleName == nameof(Data.Entities.DeliveryOrder))
            .ToListAsync(cancellationToken);

        _context.InventoryTransaction.RemoveRange(transactions);
        _context.DeliveryOrder.Remove(entity);

        await _context.SaveChangesAsync(cancellationToken);
        return true;
    }
}