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

namespace Indotalent.Features.Inventory.PositiveAdjustment.Cqrs;

public class CreatePositiveAdjustmentItemRequest
{
    public string? PositiveAdjustmentId { get; set; }
    public string? ProductId { get; set; }
    public string? WarehouseId { get; set; }
    public double? Movement { get; set; }
}

public record CreatePositiveAdjustmentItemCommand(CreatePositiveAdjustmentItemRequest Data) : IRequest<bool>;

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

    public async Task<bool> Handle(CreatePositiveAdjustmentItemCommand request, CancellationToken cancellationToken)
    {
        var master = await _context.PositiveAdjustment
            .AsNoTracking()
            .FirstOrDefaultAsync(x => x.Id == request.Data.PositiveAdjustmentId, 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.PositiveAdjustment),
            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 = request.Data.Movement
        };

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

        return true;
    }
}