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

namespace Indotalent.Features.Inventory.NegativeAdjustment.Cqrs;

public class CreateNegativeAdjustmentItemRequest
{
    public string? NegativeAdjustmentId { get; set; }
    public string? ProductId { get; set; }
    public string? WarehouseId { get; set; }
    public double? Movement { get; set; }
}

public record CreateNegativeAdjustmentItemCommand(CreateNegativeAdjustmentItemRequest Data) : IRequest<bool>;

public class CreateNegativeAdjustmentItemHandler : IRequestHandler<CreateNegativeAdjustmentItemCommand, bool>
{
    private readonly AppDbContext _context;
    public CreateNegativeAdjustmentItemHandler(AppDbContext context) => _context = context;

    public async Task<bool> Handle(CreateNegativeAdjustmentItemCommand request, CancellationToken cancellationToken)
    {
        var master = await _context.NegativeAdjustment
            .AsNoTracking()
            .FirstOrDefaultAsync(x => x.Id == request.Data.NegativeAdjustmentId, cancellationToken);

        if (master == null) return false;

        var ivtEntityName = nameof(Data.Entities.InventoryTransaction);
        var autoNoIVT = await _context.GenerateAutoNumberAsync(
            entityName: ivtEntityName,
            prefixTemplate: $"{ivtEntityName.ToShortNameConsonant(3)}/{{Year}}/",
            ct: cancellationToken
        );

        var entity = new Data.Entities.InventoryTransaction
        {
            ModuleId = master.Id,
            ModuleName = nameof(Data.Entities.NegativeAdjustment),
            ModuleCode = "ADJ-",
            ModuleNumber = master.AutoNumber,
            MovementDate = master.AdjustmentDate!.Value,
            Status = (Data.Enums.InventoryTransactionStatus)master.Status,
            AutoNumber = autoNoIVT,
            WarehouseId = request.Data.WarehouseId,
            ProductId = request.Data.ProductId,
            Movement = Math.Abs(request.Data.Movement ?? 0)
        };

        _context.CalculateInvenTrans(entity);
        _context.InventoryTransaction.Add(entity);
        await _context.SaveChangesAsync(cancellationToken);

        return true;
    }
}