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

namespace Indotalent.Features.Sales.SalesOrder.Cqrs;

public class CreateSalesOrderRequest
{
    public DateTime? OrderDate { get; set; }
    public Data.Enums.SalesOrderStatus OrderStatus { get; set; }
    public string? Description { get; set; }
    public string? CustomerId { get; set; }
    public string? TaxId { get; set; }
}

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

public record CreateSalesOrderCommand(CreateSalesOrderRequest Data) : IRequest<CreateSalesOrderResponse>;

public class CreateSalesOrderHandler : IRequestHandler<CreateSalesOrderCommand, CreateSalesOrderResponse>
{
    private readonly AppDbContext _context;
    public CreateSalesOrderHandler(AppDbContext context) => _context = context;

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

        var entity = new Data.Entities.SalesOrder
        {
            AutoNumber = autoNo,
            OrderDate = request.Data.OrderDate,
            OrderStatus = request.Data.OrderStatus,
            Description = request.Data.Description,
            CustomerId = request.Data.CustomerId,
            TaxId = request.Data.TaxId,
            BeforeTaxAmount = 0,
            TaxAmount = 0,
            AfterTaxAmount = 0
        };

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

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