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

namespace Indotalent.Features.Purchase.PurchaseRequisition.Cqrs;

public class CreatePurchaseRequisitionItemRequest
{
    public string? PurchaseRequisitionId { get; set; }
    public string? ProductId { get; set; }
    public string? Summary { get; set; }
    public decimal? UnitPrice { get; set; }
    public double? Quantity { get; set; }
}

public record CreatePurchaseRequisitionItemCommand(CreatePurchaseRequisitionItemRequest Data) : IRequest<bool>;

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

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

        if (!string.IsNullOrEmpty(request.Data.PurchaseRequisitionId))
        {
            PurchaseRequisitionHelper.Recalculate(_context, request.Data.PurchaseRequisitionId);
        }

        return true;
    }
}