using Indotalent.ConfigBackEnd.Extensions;
using Indotalent.Infrastructure.Database;
using MediatR;

namespace Indotalent.Features.Purchase.PaymentDisburse.Cqrs;

public class CreatePaymentDisburseRequest
{
    public string? BillId { 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 class CreatePaymentDisburseResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
}

public record CreatePaymentDisburseCommand(CreatePaymentDisburseRequest Data) : IRequest<CreatePaymentDisburseResponse>;

public class CreatePaymentDisburseHandler : IRequestHandler<CreatePaymentDisburseCommand, CreatePaymentDisburseResponse>
{
    private readonly AppDbContext _context;
    public CreatePaymentDisburseHandler(AppDbContext context) => _context = context;

    public async Task<CreatePaymentDisburseResponse> Handle(CreatePaymentDisburseCommand request, CancellationToken cancellationToken)
    {
        var entityName = nameof(Data.Entities.PaymentDisburse);
        var autoNo = await _context.GenerateAutoNumberAsync(
            entityName: entityName,
            prefixTemplate: $"DISB/{{Year}}/{{Month}}/",
            ct: cancellationToken
        );

        var entity = new Data.Entities.PaymentDisburse
        {
            AutoNumber = autoNo,
            BillId = request.Data.BillId,
            Description = request.Data.Description,
            PaymentDate = request.Data.PaymentDate,
            PaymentMethodId = request.Data.PaymentMethodId,
            PaymentAmount = request.Data.PaymentAmount ?? 0,
            Status = request.Data.Status
        };

        _context.PaymentDisburse.Add(entity);
        await _context.SaveChangesAsync(cancellationToken);

        return new CreatePaymentDisburseResponse
        {
            Id = entity.Id,
            AutoNumber = entity.AutoNumber
        };
    }
}