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

namespace Indotalent.Features.Sales.SalesQuotation.Cqrs;

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

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

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

        if (entity == null) return false;

        var quotationId = entity.SalesQuotationId;

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

        if (!string.IsNullOrEmpty(quotationId))
        {
            SalesQuotationHelper.Recalculate(_context, quotationId);
        }

        return true;
    }
}