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

namespace Indotalent.Features.Purchase.DebitNote.Cqrs;

public class CreateDebitNoteRequest
{
    public DateTime? DebitNoteDate { get; set; }
    public Data.Enums.DebitNoteStatus DebitNoteStatus { get; set; }
    public string? Description { get; set; }
    public string? PurchaseReturnId { get; set; }
}

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

public record CreateDebitNoteCommand(CreateDebitNoteRequest Data) : IRequest<CreateDebitNoteResponse>;

public class CreateDebitNoteHandler : IRequestHandler<CreateDebitNoteCommand, CreateDebitNoteResponse>
{
    private readonly AppDbContext _context;
    public CreateDebitNoteHandler(AppDbContext context) => _context = context;

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

        var entity = new Data.Entities.DebitNote
        {
            AutoNumber = autoNo,
            DebitNoteDate = request.Data.DebitNoteDate,
            DebitNoteStatus = request.Data.DebitNoteStatus,
            Description = request.Data.Description,
            PurchaseReturnId = request.Data.PurchaseReturnId
        };

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

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