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

namespace Indotalent.Features.Inventory.TransferIn.Cqrs;

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

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

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

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