use axum::{extract::Json, http::StatusCode, response::IntoResponse, routing::post, Router};
use serde::Deserialize;

#[derive(Deserialize)]
struct SolveRequest {
    jwt: String,
}

async fn solve_handler(Json(req): Json<SolveRequest>) -> impl IntoResponse {
    let jwt = req.jwt;
    match tokio::task::spawn_blocking(move || hcaptcha_pow::solve_jwt(&jwt)).await {
        Ok(Ok(proof)) => (StatusCode::OK, Json(serde_json::json!({ "n": proof }))),
        Ok(Err(e)) => (StatusCode::BAD_REQUEST, Json(serde_json::json!({ "error": e }))),
        Err(e) => (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(serde_json::json!({ "error": format!("Task panicked: {e}") })),
        ),
    }
}

#[tokio::main]
async fn main() {
    let app = Router::new().route("/solve", post(solve_handler));
    let addr = "0.0.0.0:3000";
    println!("hcaptcha-pow service listening on {addr}");
    let listener = tokio::net::TcpListener::bind(addr).await.unwrap();
    axum::serve(listener, app).await.unwrap();
}
