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

namespace Indotalent.Features.Sales.SalesOrder.Cqrs;

public class CreateSalesOrderItemRequest
{
    public string? SalesOrderId { get; set; }
    public string? ProductId { get; set; }
    public string? Summary { get; set; }
    public decimal? UnitPrice { get; set; }
    public double? Quantity { get; set; }
}

public record CreateSalesOrderItemCommand(CreateSalesOrderItemRequest Data) : IRequest<bool>;

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

    public async Task<bool> Handle(CreateSalesOrderItemCommand request, CancellationToken cancellationToken)
    {
        var entity = new Data.Entities.SalesOrderItem
        {
            SalesOrderId = request.Data.SalesOrderId,
            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.SalesOrderItem.Add(entity);
        await _context.SaveChangesAsync(cancellationToken);

        if (!string.IsNullOrEmpty(request.Data.SalesOrderId))
        {
            SalesOrderHelper.Recalculate(_context, request.Data.SalesOrderId);
        }

        return true;
    }
}