use contracts::ProfessionState;
use db::models::user_role_profile::UserRoleProfile;
use axum::{extract::{Path, State}, http::StatusCode, response::IntoResponse, routing::get, Json, Router};
use serde::Serialize;
use uuid::Uuid;

#[derive(Serialize)]
pub struct AdminTutorList {
    pub id: Uuid,
    pub user_role_profile_id: Uuid,
    pub user_id: Uuid,
    pub display_name: Option<String>,
    pub bio: Option<String>,
    pub location: Option<String>,
    pub status: String,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub updated_at: chrono::DateTime<chrono::Utc>,
}

impl From<UserRoleProfile> for AdminTutorList {
    fn from(p: UserRoleProfile) -> Self {
        Self {
            id: p.id,
            user_role_profile_id: p.id,
            user_id: p.user_id,
            display_name: p.display_name,
            bio: p.bio,
            location: p.location,
            status: p.status,
            created_at: p.created_at,
            updated_at: p.updated_at,
        }
    }
}

#[allow(dead_code)]
type AdminTutorDetail = AdminTutorList;

pub fn router() -> Router<ProfessionState> {
    Router::new()
        .route("/", get(list_tutors))
        .route("/{id}", get(get_tutor))
}

async fn list_tutors(
    State(state): State<ProfessionState>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
    let tutors = sqlx::query_as::<_, UserRoleProfile>(
        r#"
            SELECT id, user_id, role_key, display_name, bio, location,
                   avatar_url, phone, email, status,
                   verification_status, approval_status, rejection_reason,
                   approved_at, verified_at, is_profile_public,
                   created_at, updated_at
            FROM user_role_profiles
            WHERE role_key = 'TUTOR'
            ORDER BY created_at DESC
            LIMIT 100
        "#,
    )
    .fetch_all(&state.pool)
    .await
    .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("DB error: {e}")))?;

    let list: Vec<AdminTutorList> = tutors.into_iter().map(|p| p.into()).collect();
    Ok(Json(list))
}

async fn get_tutor(
    State(state): State<ProfessionState>,
    Path(id): Path<Uuid>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
    let tutor = sqlx::query_as::<_, UserRoleProfile>(
        r#"
            SELECT id, user_id, role_key, display_name, bio, location,
                   avatar_url, phone, email, status,
                   verification_status, approval_status, rejection_reason,
                   approved_at, verified_at, is_profile_public,
                   created_at, updated_at
            FROM user_role_profiles
            WHERE id = $1 AND role_key = 'TUTOR'
        "#,
    )
    .bind(id)
    .fetch_optional(&state.pool)
    .await
    .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("DB error: {e}")))?;

    match tutor {
        Some(t) => Ok(Json(AdminTutorList::from(t))),
        None => Err((StatusCode::NOT_FOUND, "Tutor not found".to_string())),
    }
}
