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

namespace Indotalent.Features.Sales.Invoice.Cqrs;

public class CreateInvoiceRequest
{
    public DateTime? InvoiceDate { get; set; }
    public Data.Enums.InvoiceStatus InvoiceStatus { get; set; }
    public string? Description { get; set; }
    public string? SalesOrderId { get; set; }
}

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

public record CreateInvoiceCommand(CreateInvoiceRequest Data) : IRequest<CreateInvoiceResponse>;

public class CreateInvoiceHandler : IRequestHandler<CreateInvoiceCommand, CreateInvoiceResponse>
{
    private readonly AppDbContext _context;
    public CreateInvoiceHandler(AppDbContext context) => _context = context;

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

        var entity = new Data.Entities.Invoice
        {
            AutoNumber = autoNo,
            InvoiceDate = request.Data.InvoiceDate,
            InvoiceStatus = request.Data.InvoiceStatus,
            Description = request.Data.Description,
            SalesOrderId = request.Data.SalesOrderId
        };

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

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