use scraper::{Html, Selector};

/// Enrolls a user in a list of courses
pub async fn register_course(
    user_id: i32,
    surname_first_letter: &String,
    courses: &Vec<String>,
) -> Result<(), String> {
    let courses_uri = courses
        .iter()
        .map(|course| format!("CourseList%5B%5D={}", course))
        .collect::<Vec<String>>()
        .join("&");

    let request_body = format!(
        "form_sent=1&firstLetterUser={}&firstLetterCourse=&UserList%5B%5D={}&{}",
        surname_first_letter, user_id, courses_uri
    );

    let response_html = super::session::register_courses_request(
        "/main/admin/subscribe_user2course.php".into(),
        request_body,
    )
    .await?;

    let success_selector = Selector::parse(".alert.alert-success").unwrap();

    let fragment = Html::parse_document(&response_html);

    match fragment.select(&success_selector).next() {
        Some(_) => Ok(()),
        None => Err("Error registrando curso".into()),
    }
}
