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

namespace Indotalent.Features.Sales.SalesQuotation.Cqrs;

public class UpdateSalesQuotationItemRequest
{
    public string? Id { get; set; }
    public string? ProductId { get; set; }
    public string? Summary { get; set; }
    public decimal? UnitPrice { get; set; }
    public double? Quantity { get; set; }
}

public record UpdateSalesQuotationItemCommand(UpdateSalesQuotationItemRequest Data) : IRequest<bool>;

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

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

        if (entity == null) return false;

        entity.ProductId = request.Data.ProductId;
        entity.Summary = request.Data.Summary;
        entity.UnitPrice = request.Data.UnitPrice ?? 0;
        entity.Quantity = request.Data.Quantity ?? 0;
        entity.Total = (request.Data.UnitPrice ?? 0) * (decimal)(request.Data.Quantity ?? 0);

        await _context.SaveChangesAsync(cancellationToken);

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

        return true;
    }
}