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

namespace Indotalent.Features.Inventory.Scrapping.Cqrs;

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

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

    public async Task<bool> Handle(DeleteScrappingByIdCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.Scrapping
            .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.Scrapping))
            .ToListAsync(cancellationToken);

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