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

namespace Indotalent.Features.Sales.SalesReturn.Cqrs;

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

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

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

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

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