use crate::app::AppState;
use crate::context::RequestContext;
use axum::extract::{Extension, State};
use axum::http::{HeaderMap, HeaderName, HeaderValue, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::Json;
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};
use control_plane::session_token_hash;
use serde::Serialize;

const HEADER_MNOTE_WEB_OWNER: &str = "x-mnote-web-owner";
const COOKIE_CONVEX_AUTH_JWT: &str = "__convexAuthJWT";
const COOKIE_MNOTE_SESSION: &str = "mnote_session";
const COOKIE_ACTOR_EMAIL: &str = "mnote_actor_email";
const COOKIE_ACTOR_NAME: &str = "mnote_actor_name";

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RuntimeConfigResponse {
    pub ok: bool,
    pub owner: &'static str,
    pub public_entry: String,
    pub tree_renderer_family: &'static str,
    pub document_editor_host: &'static str,
    pub legacy_next_compat_enabled: bool,
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionResponse {
    pub ok: bool,
    pub owner: &'static str,
    pub user_id: String,
    pub email: String,
    pub name: String,
    pub actor_type: String,
    pub auth_mode: &'static str,
    pub request_id: String,
    pub trace_id: String,
}

pub async fn runtime_config(State(state): State<AppState>) -> Response {
    owner_json(Json(RuntimeConfigResponse {
        ok: true,
        owner: "mnote-web",
        public_entry: state.config().public_bind_addr.clone(),
        tree_renderer_family: "rust_family",
        document_editor_host: "leptos_tiptap_island",
        legacy_next_compat_enabled: state.config().enable_legacy_next_compat,
    }))
}

pub async fn session(
    State(state): State<AppState>,
    Extension(context): Extension<RequestContext>,
) -> Response {
    owner_json(Json(build_session_response(&state, context)))
}

pub async fn refresh_session(
    State(state): State<AppState>,
    Extension(context): Extension<RequestContext>,
) -> Response {
    let mut response = owner_json(Json(build_session_response(&state, context)));
    *response.status_mut() = StatusCode::OK;
    response
}

fn build_session_response(state: &AppState, context: RequestContext) -> SessionResponse {
    if let Some(raw_token) = context
        .auth
        .cookie_header
        .as_deref()
        .and_then(|cookies| raw_cookie_value(cookies, COOKIE_MNOTE_SESSION))
    {
        let token_hash = session_token_hash(&raw_token);
        if let Ok(Some(resolved)) = state.control_plane().get_session_by_token_hash(&token_hash) {
            return SessionResponse {
                ok: true,
                owner: "mnote-web",
                user_id: resolved.user.id.clone(),
                email: resolved.user.email.unwrap_or_default(),
                name: resolved.user.display_name,
                actor_type: effective_actor_type_for_user(&resolved.user.id, &resolved.user.role),
                auth_mode: "sqliteSession",
                request_id: context.trace.request_id,
                trace_id: context.trace.trace_id,
            };
        }
    }

    let actor_id = context.auth.actor_id.trim();
    let has_forwarded_actor = !actor_id.is_empty() && actor_id != "anonymous";
    let actor_email = context
        .auth
        .cookie_header
        .as_deref()
        .and_then(|cookies| encoded_cookie_value(cookies, COOKIE_ACTOR_EMAIL))
        .or_else(|| jwt_cookie_claim(&context, &["email", "preferred_username"]));
    let actor_name = context
        .auth
        .cookie_header
        .as_deref()
        .and_then(|cookies| encoded_cookie_value(cookies, COOKIE_ACTOR_NAME))
        .or_else(|| jwt_cookie_claim(&context, &["name", "username"]));
    let user_id = if has_forwarded_actor {
        actor_id.to_string()
    } else {
        state.config().dev_user_id.clone()
    };
    let actor_type = if has_forwarded_actor {
        effective_actor_type_for_user(actor_id, &context.auth.actor_type)
    } else {
        "devFallback".to_string()
    };

    SessionResponse {
        ok: true,
        owner: "mnote-web",
        user_id,
        email: if has_forwarded_actor {
            actor_email.unwrap_or_default()
        } else {
            state.config().dev_user_email.clone()
        },
        name: if has_forwarded_actor {
            actor_name.unwrap_or_else(|| actor_id.to_string())
        } else {
            state.config().dev_user_name.clone()
        },
        actor_type,
        auth_mode: if has_forwarded_actor {
            "forwardedActor"
        } else {
            "devFallback"
        },
        request_id: context.trace.request_id,
        trace_id: context.trace.trace_id,
    }
}

fn effective_actor_type_for_user(user_id: &str, stored_role: &str) -> String {
    let role = stored_role.trim();
    let fallback_role = if role.is_empty() { "user" } else { role };
    if crate::routes::local_folder_source::is_local_access_policy_admin_actor(
        user_id,
        fallback_role,
    ) {
        "admin".to_string()
    } else {
        fallback_role.to_string()
    }
}

fn jwt_cookie_claim(context: &RequestContext, keys: &[&str]) -> Option<String> {
    let token = context
        .auth
        .cookie_header
        .as_deref()
        .and_then(|cookies| raw_cookie_value(cookies, COOKIE_CONVEX_AUTH_JWT))?;
    let payload_segment = token.split('.').nth(1)?;
    let decoded = URL_SAFE_NO_PAD.decode(payload_segment.as_bytes()).ok()?;
    let payload: serde_json::Value = serde_json::from_slice(&decoded).ok()?;
    keys.iter().find_map(|key| {
        payload
            .get(key)
            .and_then(serde_json::Value::as_str)
            .map(str::trim)
            .filter(|value| !value.is_empty())
            .map(ToOwned::to_owned)
    })
}

fn encoded_cookie_value(cookie_header: &str, name: &str) -> Option<String> {
    let encoded = raw_cookie_value(cookie_header, name)?;
    let decoded = URL_SAFE_NO_PAD.decode(encoded.as_bytes()).ok()?;
    String::from_utf8(decoded)
        .ok()
        .map(|value| value.trim().to_string())
        .filter(|value| !value.is_empty())
}

fn raw_cookie_value(cookie_header: &str, name: &str) -> Option<String> {
    cookie_header.split(';').find_map(|part| {
        let (cookie_name, cookie_value) = part.trim().split_once('=')?;
        if cookie_name.trim() == name {
            let value = cookie_value.trim();
            if value.is_empty() {
                None
            } else {
                Some(value.to_string())
            }
        } else {
            None
        }
    })
}

fn owner_json<T>(payload: Json<T>) -> Response
where
    T: Serialize,
{
    let mut response = payload.into_response();
    stamp_owner_header(response.headers_mut());
    response
}

fn stamp_owner_header(headers: &mut HeaderMap) {
    if let Ok(name) = HeaderName::from_lowercase(HEADER_MNOTE_WEB_OWNER.as_bytes()) {
        headers.insert(name, HeaderValue::from_static("mnote-web"));
    }
}

#[cfg(test)]
mod tests {
    use crate::app::{build_app, AppConfig, AppState};
    use axum::body::{to_bytes, Body};
    use axum::http::{Request, StatusCode};
    use control_plane::{session_token_hash, CreateSessionInput, UpsertUserInput};
    use tower::util::ServiceExt;

    fn app() -> axum::Router {
        build_app(AppState::new(AppConfig {
            service_name: "mnote-web".into(),
            service_version: "0.1.0".into(),
            bind_addr: "127.0.0.1:0".into(),
            public_bind_addr: "127.0.0.1:3000".into(),
            legacy_next_base_url: Some("http://127.0.0.1:3100".into()),
            enable_legacy_next_compat: true,
            enable_debug_shell_routes: false,
            enable_editor_actor: true,
            hermes_base_path: "/api/hermes".into(),
            compat_next_base_path: "/api/compat/next".into(),
            convex_url: None,
            convex_admin_key: None,
            allow_dev_fixtures: true,
            query_fixtures_json: None,
            mutation_fixtures_json: None,
            dev_user_id: "dev-user".into(),
            dev_user_name: "开发用户".into(),
            dev_user_email: "dev@mnote.local".into(),
        }))
    }

    #[tokio::test]
    async fn runtime_config_is_owned_by_mnote_web_and_hides_internal_urls() {
        let response = app()
            .oneshot(
                Request::builder()
                    .uri("/api/runtime/config")
                    .body(Body::empty())
                    .expect("request"),
            )
            .await
            .expect("response");

        assert_eq!(response.status(), StatusCode::OK);
        assert_eq!(
            response
                .headers()
                .get("x-mnote-web-owner")
                .and_then(|value| value.to_str().ok()),
            Some("mnote-web")
        );
        let body = to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("body");
        let payload: serde_json::Value = serde_json::from_slice(&body).expect("json");
        assert_eq!(payload["owner"], "mnote-web");
        assert_eq!(payload["treeRendererFamily"], "rust_family");
        assert!(payload.get("legacyNextBaseUrl").is_none());
        assert!(payload.get("convexAdminKey").is_none());
    }

    #[tokio::test]
    async fn session_handoff_returns_dev_identity_without_internal_secret() {
        let response = app()
            .oneshot(
                Request::builder()
                    .uri("/api/auth/session")
                    .body(Body::empty())
                    .expect("request"),
            )
            .await
            .expect("response");

        assert_eq!(response.status(), StatusCode::OK);
        let body = to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("body");
        let payload: serde_json::Value = serde_json::from_slice(&body).expect("json");
        assert_eq!(payload["owner"], "mnote-web");
        assert_eq!(payload["userId"], "dev-user");
        assert!(payload.get("convexAdminKey").is_none());
    }

    #[tokio::test]
    async fn session_prefers_forwarded_actor_identity_over_dev_fallback() {
        let response = app()
            .oneshot(
                Request::builder()
                    .uri("/api/auth/session")
                    .header("x-mnote-actor-id", "user_real")
                    .header("x-mnote-actor-type", "user")
                    .body(Body::empty())
                    .expect("request"),
            )
            .await
            .expect("response");

        assert_eq!(response.status(), StatusCode::OK);
        let body = to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("body");
        let payload: serde_json::Value = serde_json::from_slice(&body).expect("json");
        assert_eq!(payload["owner"], "mnote-web");
        assert_eq!(payload["userId"], "user_real");
        assert_eq!(payload["actorType"], "user");
        assert_eq!(payload["authMode"], "forwardedActor");
        assert!(payload.get("convexAdminKey").is_none());
    }

    #[tokio::test]
    async fn session_prefers_sqlite_cookie_identity_over_dev_fallback() {
        let state = AppState::new(AppConfig {
            service_name: "mnote-web".into(),
            service_version: "0.1.0".into(),
            bind_addr: "127.0.0.1:0".into(),
            public_bind_addr: "127.0.0.1:3000".into(),
            legacy_next_base_url: Some("http://127.0.0.1:3100".into()),
            enable_legacy_next_compat: true,
            enable_debug_shell_routes: false,
            enable_editor_actor: true,
            hermes_base_path: "/api/hermes".into(),
            compat_next_base_path: "/api/compat/next".into(),
            convex_url: None,
            convex_admin_key: None,
            allow_dev_fixtures: true,
            query_fixtures_json: None,
            mutation_fixtures_json: None,
            dev_user_id: "dev-user".into(),
            dev_user_name: "开发用户".into(),
            dev_user_email: "dev@mnote.local".into(),
        });
        state
            .control_plane()
            .upsert_user(UpsertUserInput {
                id: Some("shujuan".into()),
                email: Some("shujuan@163.com".into()),
                username: "shujuan".into(),
                display_name: "shujuan".into(),
                role: None,
                password_hash: None,
            })
            .expect("upsert user");
        state
            .control_plane()
            .create_session(CreateSessionInput {
                id: None,
                user_id: "shujuan".into(),
                token_hash: session_token_hash("raw-session-token"),
                user_agent: None,
                ip_hash: None,
                expires_at: None,
            })
            .expect("create session");

        let response = build_app(state)
            .oneshot(
                Request::builder()
                    .uri("/api/auth/session")
                    .header("cookie", "mnote_session=raw-session-token")
                    .body(Body::empty())
                    .expect("request"),
            )
            .await
            .expect("response");

        assert_eq!(response.status(), StatusCode::OK);
        let body = to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("body");
        let payload: serde_json::Value = serde_json::from_slice(&body).expect("json");
        assert_eq!(payload["owner"], "mnote-web");
        assert_eq!(payload["userId"], "shujuan");
        assert_eq!(payload["email"], "shujuan@163.com");
        assert_eq!(payload["name"], "shujuan");
        assert_eq!(payload["actorType"], "user");
        assert_eq!(payload["authMode"], "sqliteSession");
    }

    #[tokio::test]
    async fn session_returns_admin_for_sqlite_admin_user() {
        let state = AppState::new(AppConfig {
            service_name: "mnote-web".into(),
            service_version: "0.1.0".into(),
            bind_addr: "127.0.0.1:0".into(),
            public_bind_addr: "127.0.0.1:3000".into(),
            legacy_next_base_url: Some("http://127.0.0.1:3100".into()),
            enable_legacy_next_compat: true,
            enable_debug_shell_routes: false,
            enable_editor_actor: true,
            hermes_base_path: "/api/hermes".into(),
            compat_next_base_path: "/api/compat/next".into(),
            convex_url: None,
            convex_admin_key: None,
            allow_dev_fixtures: true,
            query_fixtures_json: None,
            mutation_fixtures_json: None,
            dev_user_id: "dev-user".into(),
            dev_user_name: "开发用户".into(),
            dev_user_email: "dev@mnote.local".into(),
        });
        state
            .control_plane()
            .upsert_user(UpsertUserInput {
                id: Some("liaibo".into()),
                email: Some("liaibo@yeah.net".into()),
                username: "liaibo".into(),
                display_name: "liaibo".into(),
                role: Some("admin".into()),
                password_hash: None,
            })
            .expect("upsert admin user");
        state
            .control_plane()
            .create_session(CreateSessionInput {
                id: None,
                user_id: "liaibo".into(),
                token_hash: session_token_hash("raw-admin-session-token"),
                user_agent: None,
                ip_hash: None,
                expires_at: None,
            })
            .expect("create admin session");

        let response = build_app(state)
            .oneshot(
                Request::builder()
                    .uri("/api/auth/session")
                    .header("cookie", "mnote_session=raw-admin-session-token")
                    .body(Body::empty())
                    .expect("request"),
            )
            .await
            .expect("response");

        assert_eq!(response.status(), StatusCode::OK);
        let body = to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("body");
        let payload: serde_json::Value = serde_json::from_slice(&body).expect("json");
        assert_eq!(payload["userId"], "liaibo");
        assert_eq!(payload["actorType"], "admin");
        assert_eq!(payload["authMode"], "sqliteSession");
    }

    #[tokio::test]
    async fn session_returns_admin_for_local_access_policy_admin() {
        let _guard = crate::test_support::hermes_env_lock()
            .lock()
            .expect("env lock");
        let policy_root = std::env::temp_dir().join(format!(
            "mnote-session-access-policy-admin-{}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&policy_root);
        std::fs::create_dir_all(&policy_root).expect("create policy root");
        let policy_file = policy_root.join("access-policy.json");
        std::fs::write(&policy_file, r#"{"admins":["liaibo"],"grants":[]}"#)
            .expect("write access policy");
        std::env::set_var("MNOTE_LOCAL_ACCESS_POLICY_FILE", &policy_file);

        let state = AppState::new(AppConfig {
            service_name: "mnote-web".into(),
            service_version: "0.1.0".into(),
            bind_addr: "127.0.0.1:0".into(),
            public_bind_addr: "127.0.0.1:3000".into(),
            legacy_next_base_url: Some("http://127.0.0.1:3100".into()),
            enable_legacy_next_compat: true,
            enable_debug_shell_routes: false,
            enable_editor_actor: true,
            hermes_base_path: "/api/hermes".into(),
            compat_next_base_path: "/api/compat/next".into(),
            convex_url: None,
            convex_admin_key: None,
            allow_dev_fixtures: true,
            query_fixtures_json: None,
            mutation_fixtures_json: None,
            dev_user_id: "dev-user".into(),
            dev_user_name: "开发用户".into(),
            dev_user_email: "dev@mnote.local".into(),
        });
        state
            .control_plane()
            .upsert_user(UpsertUserInput {
                id: Some("liaibo".into()),
                email: Some("liaibo@yeah.net".into()),
                username: "liaibo".into(),
                display_name: "liaibo".into(),
                role: None,
                password_hash: None,
            })
            .expect("upsert policy admin user");
        state
            .control_plane()
            .create_session(CreateSessionInput {
                id: None,
                user_id: "liaibo".into(),
                token_hash: session_token_hash("raw-policy-admin-session-token"),
                user_agent: None,
                ip_hash: None,
                expires_at: None,
            })
            .expect("create policy admin session");

        let response = build_app(state)
            .oneshot(
                Request::builder()
                    .uri("/api/auth/session")
                    .header("cookie", "mnote_session=raw-policy-admin-session-token")
                    .body(Body::empty())
                    .expect("request"),
            )
            .await
            .expect("response");

        std::env::remove_var("MNOTE_LOCAL_ACCESS_POLICY_FILE");
        let _ = std::fs::remove_dir_all(&policy_root);

        assert_eq!(response.status(), StatusCode::OK);
        let body = to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("body");
        let payload: serde_json::Value = serde_json::from_slice(&body).expect("json");
        assert_eq!(payload["userId"], "liaibo");
        assert_eq!(payload["actorType"], "admin");
        assert_eq!(payload["authMode"], "sqliteSession");
    }

    #[tokio::test]
    async fn legacy_whoami_alias_prefers_forwarded_actor_identity() {
        let response = app()
            .oneshot(
                Request::builder()
                    .uri("/api/auth/whoami")
                    .header("x-mnote-actor-id", "user_real")
                    .header("x-mnote-actor-type", "user")
                    .body(Body::empty())
                    .expect("request"),
            )
            .await
            .expect("response");

        assert_eq!(response.status(), StatusCode::OK);
        let body = to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("body");
        let payload: serde_json::Value = serde_json::from_slice(&body).expect("json");
        assert_eq!(payload["owner"], "mnote-web");
        assert_eq!(payload["userId"], "user_real");
        assert_eq!(payload["actorType"], "user");
        assert_eq!(payload["authMode"], "forwardedActor");
        assert_ne!(payload["code"], "legacy_next_compat_disabled");
    }

    #[tokio::test]
    async fn legacy_whoami_alias_returns_dev_identity() {
        let response = app()
            .oneshot(
                Request::builder()
                    .uri("/api/auth/whoami")
                    .body(Body::empty())
                    .expect("request"),
            )
            .await
            .expect("response");

        assert_eq!(response.status(), StatusCode::OK);
        let body = to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("body");
        let payload: serde_json::Value = serde_json::from_slice(&body).expect("json");
        assert_eq!(payload["owner"], "mnote-web");
        assert_eq!(payload["userId"], "dev-user");
        assert_ne!(payload["code"], "legacy_next_compat_disabled");
    }

    #[tokio::test]
    async fn legacy_mnote_web_token_alias_returns_dev_identity() {
        let response = app()
            .oneshot(
                Request::builder()
                    .uri("/api/auth/mnote-web-token")
                    .body(Body::empty())
                    .expect("request"),
            )
            .await
            .expect("response");

        assert_eq!(response.status(), StatusCode::OK);
        let body = to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("body");
        let payload: serde_json::Value = serde_json::from_slice(&body).expect("json");
        assert_eq!(payload["owner"], "mnote-web");
        assert_eq!(payload["userId"], "dev-user");
        assert_ne!(payload["code"], "legacy_next_compat_disabled");
    }
}
