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

namespace Indotalent.Features.Sales.SalesQuotation.Cqrs;

public class CreateSalesQuotationItemRequest
{
    public string? SalesQuotationId { get; set; }
    public string? ProductId { get; set; }
    public string? Summary { get; set; }
    public decimal? UnitPrice { get; set; }
    public double? Quantity { get; set; }
}

public record CreateSalesQuotationItemCommand(CreateSalesQuotationItemRequest Data) : IRequest<bool>;

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

    public async Task<bool> Handle(CreateSalesQuotationItemCommand request, CancellationToken cancellationToken)
    {
        var entity = new Data.Entities.SalesQuotationItem
        {
            SalesQuotationId = request.Data.SalesQuotationId,
            ProductId = request.Data.ProductId,
            Summary = request.Data.Summary,
            UnitPrice = request.Data.UnitPrice ?? 0,
            Quantity = request.Data.Quantity ?? 0,
            Total = (request.Data.UnitPrice ?? 0) * (decimal)(request.Data.Quantity ?? 0)
        };

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

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

        return true;
    }
}