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

namespace Indotalent.Features.Purchase.PurchaseReturn.Cqrs;

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

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

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

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

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