//! Public email capture for the nxtgauge.com coming-soon page
//! (nxtgauge-gitops/coming-soon/index.html's "Notify Me" form).
//! Deliberately unauthenticated - anyone can submit an email, same trust
//! model as a newsletter signup form.

use crate::AppState;
use axum::{extract::State, http::StatusCode, routing::post, Json, Router};
use serde::{Deserialize, Serialize};

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

#[derive(Debug, Deserialize)]
struct JoinWaitlistRequest {
    email: String,
}

#[derive(Debug, Serialize)]
struct JoinWaitlistResponse {
    joined: bool,
}

async fn join_waitlist(
    State(state): State<AppState>,
    Json(body): Json<JoinWaitlistRequest>,
) -> Result<Json<JoinWaitlistResponse>, (StatusCode, String)> {
    let email = body.email.trim().to_lowercase();

    // Deliberately loose validation (just "has an @ and something on both
    // sides") - this is a pre-launch marketing signup, not an account, and
    // being too strict just loses real signups to typos in TLDs etc.
    let valid = {
        let mut parts = email.splitn(2, '@');
        matches!((parts.next(), parts.next()), (Some(local), Some(domain)) if !local.is_empty() && domain.contains('.'))
    };
    if !valid || email.len() > 255 {
        return Err((StatusCode::BAD_REQUEST, "Please enter a valid email address".to_string()));
    }

    sqlx::query(
        "INSERT INTO waitlist_signups (email) VALUES ($1) ON CONFLICT (email) DO NOTHING",
    )
    .bind(&email)
    .execute(&state.pool)
    .await
    .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, format!("DB error: {e}")))?;

    Ok(Json(JoinWaitlistResponse { joined: true }))
}
