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

namespace Indotalent.Features.Sales.CreditNote.Cqrs;

public class CreateCreditNoteRequest
{
    public DateTime? CreditNoteDate { get; set; }
    public Data.Enums.CreditNoteStatus CreditNoteStatus { get; set; }
    public string? Description { get; set; }
    public string? SalesReturnId { get; set; }
}

public class CreateCreditNoteResponse
{
    public string? Id { get; set; }
    public string? AutoNumber { get; set; }
}

public record CreateCreditNoteCommand(CreateCreditNoteRequest Data) : IRequest<CreateCreditNoteResponse>;

public class CreateCreditNoteHandler : IRequestHandler<CreateCreditNoteCommand, CreateCreditNoteResponse>
{
    private readonly AppDbContext _context;
    public CreateCreditNoteHandler(AppDbContext context) => _context = context;

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

        var entity = new Data.Entities.CreditNote
        {
            AutoNumber = autoNo,
            CreditNoteDate = request.Data.CreditNoteDate,
            CreditNoteStatus = request.Data.CreditNoteStatus,
            Description = request.Data.Description,
            SalesReturnId = request.Data.SalesReturnId
        };

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

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