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

namespace Indotalent.Features.Inventory.StockCount.Cqrs;

public class UpdateStockCountItemRequest
{
    public string? Id { get; set; }
    public string? ProductId { get; set; }
    public double? QtySCCount { get; set; }
}

public record UpdateStockCountItemCommand(UpdateStockCountItemRequest Data) : IRequest<bool>;

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

    public async Task<bool> Handle(UpdateStockCountItemCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.InventoryTransaction
            .FirstOrDefaultAsync(x => x.Id == request.Data.Id, cancellationToken);

        if (entity == null) return false;

        entity.ProductId = request.Data.ProductId;
        entity.QtySCCount = Math.Abs(request.Data.QtySCCount ?? 0);

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

        return true;
    }
}