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

namespace Indotalent.Features.Sales.SalesOrder.Cqrs;

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

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

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

        if (entity == null) return false;

        var salesOrderId = entity.SalesOrderId;

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

        if (!string.IsNullOrEmpty(salesOrderId))
        {
            SalesOrderHelper.Recalculate(_context, salesOrderId);
        }

        return true;
    }
}