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

namespace Indotalent.Features.Purchase.GoodsReceive.Cqrs;

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

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

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

        if (entity == null) return false;

        var transactions = await _context.InventoryTransaction
            .Where(x => x.ModuleId == entity.Id && x.ModuleName == nameof(Data.Entities.GoodsReceive))
            .ToListAsync(cancellationToken);

        _context.InventoryTransaction.RemoveRange(transactions);
        _context.GoodsReceive.Remove(entity);

        await _context.SaveChangesAsync(cancellationToken);
        return true;
    }
}