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

namespace Indotalent.Features.Purchase.PurchaseRequisition.Cqrs;

public class CreatePurchaseRequisitionRequest
{
    public DateTime? RequisitionDate { get; set; }
    public Data.Enums.PurchaseRequisitionStatus RequisitionStatus { get; set; }
    public string? Description { get; set; }
    public string? VendorId { get; set; }
    public string? TaxId { get; set; }
}

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

public record CreatePurchaseRequisitionCommand(CreatePurchaseRequisitionRequest Data) : IRequest<CreatePurchaseRequisitionResponse>;

public class CreatePurchaseRequisitionHandler : IRequestHandler<CreatePurchaseRequisitionCommand, CreatePurchaseRequisitionResponse>
{
    private readonly AppDbContext _context;
    public CreatePurchaseRequisitionHandler(AppDbContext context) => _context = context;

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

        var entity = new Data.Entities.PurchaseRequisition
        {
            AutoNumber = autoNo,
            RequisitionDate = request.Data.RequisitionDate,
            RequisitionStatus = request.Data.RequisitionStatus,
            Description = request.Data.Description,
            VendorId = request.Data.VendorId,
            TaxId = request.Data.TaxId,
            BeforeTaxAmount = 0,
            TaxAmount = 0,
            AfterTaxAmount = 0
        };

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

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