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

namespace Indotalent.Features.Purchase.PurchaseRequisition.Cqrs;

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

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

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

        if (entity == null) return false;

        var requisitionId = entity.PurchaseRequisitionId;

        _context.PurchaseRequisitionItem.Remove(entity);
        await _context.SaveChangesAsync(cancellationToken);

        if (!string.IsNullOrEmpty(requisitionId))
        {
            PurchaseRequisitionHelper.Recalculate(_context, requisitionId);
        }

        return true;
    }
}