use crate::models::AuthInfo;
use dioxus::prelude::*;

/// Check the current user's authentication state.
///
/// Reads the tower-sessions session on the server and returns an
/// [`AuthInfo`] describing the logged-in user. When no valid session
/// exists, `authenticated` is `false` and all other fields are empty.
///
/// # Errors
///
/// Returns `ServerFnError` if the session store cannot be read.
#[server(endpoint = "check-auth")]
pub async fn check_auth() -> Result<AuthInfo, ServerFnError> {
    use crate::infrastructure::auth::LOGGED_IN_USER_SESS_KEY;
    use crate::infrastructure::state::UserStateInner;
    use dioxus_fullstack::FullstackContext;

    let session: tower_sessions::Session = FullstackContext::extract().await?;

    let user_state: Option<UserStateInner> = session
        .get(LOGGED_IN_USER_SESS_KEY)
        .await
        .map_err(|e| ServerFnError::new(format!("session read failed: {e}")))?;

    match user_state {
        Some(u) => {
            let librechat_url =
                std::env::var("LIBRECHAT_URL").unwrap_or_else(|_| "http://localhost:3080".into());

            // Extract service URLs from server state so the frontend can
            // embed developer tools (LangGraph, LangFlow, Langfuse).
            let state: crate::infrastructure::server_state::ServerState =
                FullstackContext::extract().await?;
            let langgraph_url = state.services.langgraph_url.clone();
            let langflow_url = state.services.langflow_url.clone();
            let langfuse_url = state.services.langfuse_url.clone();
            let compliance_scanner_url = state.services.compliance_scanner_url.clone();

            Ok(AuthInfo {
                authenticated: true,
                sub: u.sub,
                email: u.user.email,
                name: u.user.name,
                avatar_url: u.user.avatar_url,
                librechat_url,
                langgraph_url,
                langflow_url,
                langfuse_url,
                compliance_scanner_url,
            })
        }
        None => Ok(AuthInfo::default()),
    }
}
