use crate::AppState;
use db::models::requirement::Requirement;
use axum::{extract::State, http::StatusCode, response::IntoResponse, routing::get, Json, Router};
use serde::Serialize;
use uuid::Uuid;

#[derive(Serialize)]
pub struct AdminLeadRow {
    pub id: Uuid,
    pub title: String,
    pub description: Option<String>,
    pub profession_key: String,
    pub location: String,
    pub budget_inr: Option<i32>,
    pub status: String,
    pub created_at: chrono::DateTime<chrono::Utc>,
    pub updated_at: chrono::DateTime<chrono::Utc>,
}

impl From<Requirement> for AdminLeadRow {
    fn from(r: Requirement) -> Self {
        Self {
            id: r.id,
            title: r.title,
            description: Some(r.description),
            profession_key: r.profession_key,
            location: r.location,
             budget_inr: r.budget_inr,
            status: r.status,
            created_at: r.created_at,
            updated_at: r.updated_at,
        }
    }
}

pub fn router() -> Router<AppState> {
    Router::new().route("/", get(list_leads))
}

async fn list_leads(
    State(state): State<AppState>,
) -> Result<impl IntoResponse, (StatusCode, String)> {
    let requirements = sqlx::query_as::<_, Requirement>(
        r#"
            SELECT id, created_by_user_id, profession_key, title, description, location, budget_inr,
                   required_date, extra_data_json, status, rejection_reason, request_count, accepted_count,
                   expires_at, approved_at, approved_by, created_at, updated_at
            FROM leads
            ORDER BY created_at DESC
            LIMIT 100
        "#,
    )
    .fetch_all(&state.pool)
    .await
    .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("DB error: {e}")))?;

    let leads: Vec<AdminLeadRow> = requirements.into_iter().map(|r| r.into()).collect();
    Ok(Json(leads))
}
