namespace Application.Enrollments.Commands;

using Domain.Exceptions;
using Domain.Ports.Repositories;
using MediatR;

public record UnenrollStudentCommand(int EnrollmentId) : IRequest<bool>;

public class UnenrollStudentHandler(
    IEnrollmentRepository enrollmentRepository,
    IStudentRepository studentRepository,
    IUnitOfWork unitOfWork)
    : IRequestHandler<UnenrollStudentCommand, bool>
{
    public async Task<bool> Handle(UnenrollStudentCommand request, CancellationToken ct)
    {
        var enrollment = await enrollmentRepository.GetByIdAsync(request.EnrollmentId, ct)
            ?? throw new EnrollmentNotFoundException(request.EnrollmentId);

        var student = await studentRepository.GetByIdWithEnrollmentsAsync(enrollment.StudentId, ct);
        student?.RemoveEnrollment(enrollment);

        enrollmentRepository.Delete(enrollment);
        await unitOfWork.SaveChangesAsync(ct);

        return true;
    }
}
