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

namespace Indotalent.Features.Pipeline.Expense.Cqrs;

public record DeleteExpenseByIdRequest(string Id);

public record DeleteExpenseByIdCommand(DeleteExpenseByIdRequest Data) : IRequest<bool>;

public class DeleteExpenseByIdHandler : IRequestHandler<DeleteExpenseByIdCommand, bool>
{
    private readonly AppDbContext _context;

    public DeleteExpenseByIdHandler(AppDbContext context) => _context = context;

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

        if (entity == null) return false;

        _context.Expense.Remove(entity);
        return await _context.SaveChangesAsync(cancellationToken) > 0;
    }
}