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

namespace Indotalent.Features.Inventory.TransferIn.Cqrs;

public class CreateTransferInItemRequest
{
    public string? TransferInId { get; set; }
    public string? ProductId { get; set; }
    public double? Movement { get; set; }
}

public record CreateTransferInItemCommand(CreateTransferInItemRequest Data) : IRequest<bool>;

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

    public async Task<bool> Handle(CreateTransferInItemCommand request, CancellationToken cancellationToken)
    {
        var master = await _context.TransferIn
            .AsNoTracking()
            .Include(x => x.TransferOut)
            .FirstOrDefaultAsync(x => x.Id == request.Data.TransferInId, cancellationToken);

        if (master == null || master.TransferOut == 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.TransferIn),
            ModuleCode = "TO-IN",
            ModuleNumber = master.AutoNumber,
            MovementDate = master.TransferReceiveDate!.Value,
            Status = (Data.Enums.InventoryTransactionStatus)master.Status,
            AutoNumber = autoNoIVT,
            WarehouseId = master.TransferOut.WarehouseToId,
            ProductId = request.Data.ProductId,
            Movement = request.Data.Movement
        };

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

        return true;
    }
}