using Application.Students.DTOs;
using Domain.Ports.Repositories;
using MediatR;

namespace Application.Auth.Queries;

public record ValidateActivationCodeQuery(string Code) : IRequest<ActivationValidationResult>;

public class ValidateActivationCodeHandler(
    IStudentRepository studentRepository,
    IPasswordService passwordService
) : IRequestHandler<ValidateActivationCodeQuery, ActivationValidationResult>
{
    public async Task<ActivationValidationResult> Handle(ValidateActivationCodeQuery request, CancellationToken ct)
    {
        var students = await studentRepository.GetPendingActivationAsync(ct);

        var student = students.FirstOrDefault(s =>
            s.ActivationCodeHash != null &&
            passwordService.VerifyPassword(request.Code, s.ActivationCodeHash));

        if (student == null)
            return new ActivationValidationResult(false, null, "Codigo de activacion invalido");

        if (student.IsActivationExpired())
            return new ActivationValidationResult(false, null, "El codigo de activacion ha expirado");

        return new ActivationValidationResult(true, student.Name, null);
    }
}
