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

namespace Indotalent.Features.Purchase.PurchaseOrder.Cqrs;

public class CreatePurchaseOrderRequest
{
    public DateTime? OrderDate { get; set; }
    public Data.Enums.PurchaseOrderStatus OrderStatus { get; set; }
    public string? Description { get; set; }
    public string? VendorId { get; set; }
    public string? TaxId { get; set; }
}

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

public record CreatePurchaseOrderCommand(CreatePurchaseOrderRequest Data) : IRequest<CreatePurchaseOrderResponse>;

public class CreatePurchaseOrderHandler : IRequestHandler<CreatePurchaseOrderCommand, CreatePurchaseOrderResponse>
{
    private readonly AppDbContext _context;
    public CreatePurchaseOrderHandler(AppDbContext context) => _context = context;

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

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

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

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