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

namespace Indotalent.Features.Inventory.StockCount.Cqrs;

public record DeleteStockCountByIdCommand(string Id) : IRequest<bool>;

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

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

        if (entity == null) return false;

        var items = await _context.InventoryTransaction
            .Where(x => x.ModuleId == request.Id && x.ModuleName == nameof(Data.Entities.StockCount))
            .ToListAsync(cancellationToken);

        _context.InventoryTransaction.RemoveRange(items);
        _context.StockCount.Remove(entity);
        await _context.SaveChangesAsync(cancellationToken);
        return true;
    }
}