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

namespace Indotalent.Features.Purchase.PurchaseRequisition.Cqrs;

public class UpdatePurchaseRequisitionRequest
{
    public string? Id { get; set; }
    public DateTime? RequisitionDate { get; set; }
    public Data.Enums.PurchaseRequisitionStatus RequisitionStatus { get; set; }
    public string? AutoNumber { get; set; }
    public string? Description { get; set; }
    public string? VendorId { get; set; }
    public string? TaxId { get; set; }
    public decimal? BeforeTaxAmount { get; set; }
    public decimal? TaxAmount { get; set; }
    public decimal? AfterTaxAmount { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

public record UpdatePurchaseRequisitionCommand(UpdatePurchaseRequisitionRequest Data) : IRequest<bool>;

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

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

        if (entity == null) return false;

        entity.RequisitionDate = request.Data.RequisitionDate;
        entity.RequisitionStatus = request.Data.RequisitionStatus;
        entity.Description = request.Data.Description;
        entity.VendorId = request.Data.VendorId;
        entity.TaxId = request.Data.TaxId;

        await _context.SaveChangesAsync(cancellationToken);

        if (!string.IsNullOrEmpty(entity.Id))
        {
            PurchaseRequisitionHelper.Recalculate(_context, entity.Id);
        }

        return true;
    }
}