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

namespace Indotalent.Features.Sales.PaymentReceive.Cqrs;

public class UpdatePaymentReceiveRequest
{
    public string? Id { get; set; }
    public string? InvoiceId { 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.PaymentReceiveStatus 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 UpdatePaymentReceiveCommand(UpdatePaymentReceiveRequest Data) : IRequest<bool>;

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

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

        if (entity == null) return false;

        entity.InvoiceId = request.Data.InvoiceId;
        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;
    }
}