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

namespace Indotalent.Features.Sales.PaymentReceive.Cqrs;

public class CreatePaymentReceiveRequest
{
    public string? InvoiceId { 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 class CreatePaymentReceiveResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
}

public record CreatePaymentReceiveCommand(CreatePaymentReceiveRequest Data) : IRequest<CreatePaymentReceiveResponse>;

public class CreatePaymentReceiveHandler : IRequestHandler<CreatePaymentReceiveCommand, CreatePaymentReceiveResponse>
{
    private readonly AppDbContext _context;
    public CreatePaymentReceiveHandler(AppDbContext context) => _context = context;

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

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

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

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