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

namespace Indotalent.Features.Inventory.TransferOut.Cqrs;

public class CreateTransferOutItemRequest
{
    public string? TransferOutId { get; set; }
    public string? ProductId { get; set; }
    public double? Movement { get; set; }
}

public record CreateTransferOutItemCommand(CreateTransferOutItemRequest Data) : IRequest<bool>;

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

    public async Task<bool> Handle(CreateTransferOutItemCommand request, CancellationToken cancellationToken)
    {
        var master = await _context.TransferOut
            .AsNoTracking()
            .FirstOrDefaultAsync(x => x.Id == request.Data.TransferOutId, 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.TransferOut),
            ModuleCode = "TO-OUT",
            ModuleNumber = master.AutoNumber,
            MovementDate = master.TransferReleaseDate!.Value,
            Status = (Data.Enums.InventoryTransactionStatus)master.Status,
            AutoNumber = autoNoIVT,
            WarehouseId = master.WarehouseFromId,
            ProductId = request.Data.ProductId,
            Movement = request.Data.Movement
        };

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

        return true;
    }
}