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 serde::Serialize;

const HEADER_MNOTE_WEB_OWNER: &str = "x-mnote-web-owner";

#[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 {
    let actor_id = context.auth.actor_id.trim();
    let has_forwarded_actor = !actor_id.is_empty() && actor_id != "anonymous";
    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 {
        context.auth.actor_type
    } else {
        "devFallback".to_string()
    };

    SessionResponse {
        ok: true,
        owner: "mnote-web",
        user_id,
        email: if has_forwarded_actor {
            String::new()
        } else {
            state.config().dev_user_email.clone()
        },
        name: if has_forwarded_actor {
            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 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 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,
            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 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");
    }
}
