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

namespace Indotalent.Features.Purchase.PurchaseOrder.Cqrs;

public class UpdatePurchaseOrderRequest
{
    public string? Id { get; set; }
    public DateTime? OrderDate { get; set; }
    public Data.Enums.PurchaseOrderStatus OrderStatus { 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 UpdatePurchaseOrderCommand(UpdatePurchaseOrderRequest Data) : IRequest<bool>;

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

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

        if (entity == null) return false;

        entity.OrderDate = request.Data.OrderDate;
        entity.OrderStatus = request.Data.OrderStatus;
        entity.Description = request.Data.Description;
        entity.VendorId = request.Data.VendorId;
        entity.TaxId = request.Data.TaxId;

        await _context.SaveChangesAsync(cancellationToken);

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

        return true;
    }
}