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

namespace Indotalent.Features.Inventory.PositiveAdjustment.Cqrs;

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

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

public record CreatePositiveAdjustmentCommand(CreatePositiveAdjustmentRequest Data) : IRequest<CreatePositiveAdjustmentResponse>;

public class CreatePositiveAdjustmentHandler : IRequestHandler<CreatePositiveAdjustmentCommand, CreatePositiveAdjustmentResponse>
{
    private readonly AppDbContext _context;
    public CreatePositiveAdjustmentHandler(AppDbContext context) => _context = context;

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

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

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

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