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

namespace Indotalent.Features.Inventory.Scrapping.Cqrs;

public class CreateScrappingItemRequest
{
    public string? ScrappingId { get; set; }
    public string? ProductId { get; set; }
    public double? Movement { get; set; }
}

public record CreateScrappingItemCommand(CreateScrappingItemRequest Data) : IRequest<bool>;

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

    public async Task<bool> Handle(CreateScrappingItemCommand request, CancellationToken cancellationToken)
    {
        var master = await _context.Scrapping
            .AsNoTracking()
            .FirstOrDefaultAsync(x => x.Id == request.Data.ScrappingId, 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.Scrapping),
            ModuleCode = "SCRP",
            ModuleNumber = master.AutoNumber,
            MovementDate = master.ScrappingDate!.Value,
            Status = (Data.Enums.InventoryTransactionStatus)master.Status,
            AutoNumber = autoNoIVT,
            WarehouseId = master.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;
    }
}