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

namespace Indotalent.Features.Inventory.NegativeAdjustment.Cqrs;

public class CreateNegativeAdjustmentRequest
{
    public DateTime? AdjustmentDate { get; set; }
    public Data.Enums.AdjustmentStatus Status { get; set; }
    public string? Description { get; set; }
}

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

public record CreateNegativeAdjustmentCommand(CreateNegativeAdjustmentRequest Data) : IRequest<CreateNegativeAdjustmentResponse>;

public class CreateNegativeAdjustmentHandler : IRequestHandler<CreateNegativeAdjustmentCommand, CreateNegativeAdjustmentResponse>
{
    private readonly AppDbContext _context;
    public CreateNegativeAdjustmentHandler(AppDbContext context) => _context = context;

    public async Task<CreateNegativeAdjustmentResponse> Handle(CreateNegativeAdjustmentCommand request, CancellationToken cancellationToken)
    {
        var entityName = nameof(Data.Entities.NegativeAdjustment);
        var autoNo = await _context.GenerateAutoNumberAsync(
            entityName: entityName,
            prefixTemplate: $"{entityName.ToShortNameConsonant(3)}/{{Year}}/",
            ct: cancellationToken
        );

        var entity = new Data.Entities.NegativeAdjustment
        {
            AutoNumber = autoNo,
            AdjustmentDate = request.Data.AdjustmentDate,
            Status = request.Data.Status,
            Description = request.Data.Description
        };

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

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