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

namespace Indotalent.Features.Pipeline.Budget.Cqrs;

public record DeleteBudgetByIdRequest(string Id);

public record DeleteBudgetByIdCommand(DeleteBudgetByIdRequest Data) : IRequest<bool>;

public class DeleteBudgetByIdHandler : IRequestHandler<DeleteBudgetByIdCommand, bool>
{
    private readonly AppDbContext _context;

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

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

        if (entity == null) return false;

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