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

namespace Indotalent.Features.Pipeline.SalesRepresentative.Cqrs;

public record DeleteSalesRepresentativeByIdRequest(string Id);

public record DeleteSalesRepresentativeByIdCommand(DeleteSalesRepresentativeByIdRequest Data) : IRequest<bool>;

public class DeleteSalesRepresentativeByIdHandler : IRequestHandler<DeleteSalesRepresentativeByIdCommand, bool>
{
    private readonly AppDbContext _context;

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

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

        if (entity == null) return false;

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