use actix_web::web;

use crate::AppState;
use crate::error::{Error, Result};
use crate::user::RepositoryDefinition;

pub async fn validate_repo(
    app_state: web::Data<AppState>,
    repo: &RepositoryDefinition,
    user_id: &str,
) -> Result<()> {
    let token = app_state.user.get_access_token(&user_id).await?;
    let response = app_state
        .reqwest_client
        .get(format!(
            "https://raw.githubusercontent.com/{}/HEAD/dist/index.html",
            repo.full_name
        ))
        .bearer_auth(token)
        .send()
        .await?;

    match response.status() {
        reqwest::StatusCode::OK => Ok(()),
        reqwest::StatusCode::NOT_FOUND => Err(Error::ValidationFailed(
            "dist/index.html not found in repository".to_string(),
        )),
        status => Err(Error::ValidationFailed(format!(
            "failed to validate repository: HTTP {}",
            status
        ))),
    }
}
