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

namespace Indotalent.Features.Purchase.PaymentDisburse.Cqrs;

public class UpdatePaymentDisburseRequest
{
    public string? Id { get; set; }
    public string? BillId { get; set; }
    public string? AutoNumber { get; set; }
    public string? Description { get; set; }
    public DateTime? PaymentDate { get; set; }
    public string? PaymentMethodId { get; set; }
    public decimal? PaymentAmount { get; set; }
    public Data.Enums.PaymentDisburseStatus Status { get; set; }
    public DateTimeOffset? CreatedAt { get; set; }
    public string? CreatedBy { get; set; }
    public DateTimeOffset? UpdatedAt { get; set; }
    public string? UpdatedBy { get; set; }
}

public record UpdatePaymentDisburseCommand(UpdatePaymentDisburseRequest Data) : IRequest<bool>;

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

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

        if (entity == null) return false;

        entity.BillId = request.Data.BillId;
        entity.Description = request.Data.Description;
        entity.PaymentDate = request.Data.PaymentDate;
        entity.PaymentMethodId = request.Data.PaymentMethodId;
        entity.PaymentAmount = request.Data.PaymentAmount ?? 0;
        entity.Status = request.Data.Status;

        await _context.SaveChangesAsync(cancellationToken);
        return true;
    }
}