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

namespace Indotalent.Features.Sales.SalesQuotation.Cqrs;

public class CreateSalesQuotationRequest
{
    public DateTime? QuotationDate { get; set; }
    public Data.Enums.SalesQuotationStatus QuotationStatus { get; set; }
    public string? Description { get; set; }
    public string? CustomerId { get; set; }
    public string? TaxId { get; set; }
}

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

public record CreateSalesQuotationCommand(CreateSalesQuotationRequest Data) : IRequest<CreateSalesQuotationResponse>;

public class CreateSalesQuotationHandler : IRequestHandler<CreateSalesQuotationCommand, CreateSalesQuotationResponse>
{
    private readonly AppDbContext _context;
    public CreateSalesQuotationHandler(AppDbContext context) => _context = context;

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

        var entity = new Data.Entities.SalesQuotation
        {
            AutoNumber = autoNo,
            QuotationDate = request.Data.QuotationDate,
            QuotationStatus = request.Data.QuotationStatus,
            Description = request.Data.Description,
            CustomerId = request.Data.CustomerId,
            TaxId = request.Data.TaxId,
            BeforeTaxAmount = 0,
            TaxAmount = 0,
            AfterTaxAmount = 0
        };

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

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