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

namespace Indotalent.Features.Inventory.PositiveAdjustment.Cqrs;

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

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

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

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