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

namespace Indotalent.Features.Inventory.StockCount.Cqrs;

public class CreateStockCountItemRequest
{
    public string? StockCountId { get; set; }
    public string? ProductId { get; set; }
    public double? QtySCCount { get; set; }
}

public record CreateStockCountItemCommand(CreateStockCountItemRequest Data) : IRequest<bool>;

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

    public async Task<bool> Handle(CreateStockCountItemCommand request, CancellationToken cancellationToken)
    {
        var master = await _context.StockCount
            .AsNoTracking()
            .FirstOrDefaultAsync(x => x.Id == request.Data.StockCountId, 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.StockCount),
            ModuleCode = "COUNT",
            ModuleNumber = master.AutoNumber,
            MovementDate = master.CountDate!.Value,
            Status = (Data.Enums.InventoryTransactionStatus)master.Status,
            AutoNumber = autoNoIVT,
            WarehouseId = master.WarehouseId,
            ProductId = request.Data.ProductId,
            QtySCCount = Math.Abs(request.Data.QtySCCount ?? 0)
        };

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

        return true;
    }
}