use loco_rs::prelude::*;
use serde::{Deserialize, Serialize};

use axum::http::header;

use crate::services::{abuse_guard, admin_audit, subscriptions, turnstile};

#[derive(Clone, Debug, Deserialize)]
pub struct PublicSubscriptionPayload {
    pub email: String,
    #[serde(default, alias = "displayName")]
    pub display_name: Option<String>,
    #[serde(default)]
    pub source: Option<String>,
    #[serde(default, alias = "turnstileToken")]
    pub turnstile_token: Option<String>,
}

#[derive(Clone, Debug, Deserialize)]
pub struct PublicBrowserPushSubscriptionPayload {
    pub subscription: serde_json::Value,
    #[serde(default)]
    pub source: Option<String>,
    #[serde(default, alias = "turnstileToken")]
    pub turnstile_token: Option<String>,
}

#[derive(Clone, Debug, Deserialize)]
pub struct SubscriptionTokenPayload {
    pub token: String,
}

#[derive(Clone, Debug, Deserialize)]
pub struct SubscriptionManageQuery {
    pub token: String,
}

#[derive(Clone, Debug, Deserialize)]
pub struct SubscriptionManageUpdatePayload {
    pub token: String,
    #[serde(default, alias = "displayName")]
    pub display_name: Option<String>,
    #[serde(default)]
    pub status: Option<String>,
    #[serde(default)]
    pub filters: Option<serde_json::Value>,
}

#[derive(Clone, Debug, Serialize)]
pub struct PublicSubscriptionResponse {
    pub ok: bool,
    pub subscription_id: i32,
    pub status: String,
    pub requires_confirmation: bool,
    pub message: String,
}

#[derive(Clone, Debug, Serialize)]
pub struct SubscriptionManageResponse {
    pub ok: bool,
    pub subscription: subscriptions::PublicSubscriptionView,
}

fn public_subscription_metadata(source: Option<String>) -> serde_json::Value {
    serde_json::json!({
        "source": source,
        "kind": "public-form",
    })
}

fn public_browser_push_metadata(
    source: Option<String>,
    subscription: serde_json::Value,
    user_agent: Option<String>,
) -> serde_json::Value {
    serde_json::json!({
        "source": source,
        "kind": "browser-push",
        "subscription": subscription,
        "user_agent": user_agent,
    })
}

#[debug_handler]
pub async fn subscribe(
    State(ctx): State<AppContext>,
    headers: axum::http::HeaderMap,
    Json(payload): Json<PublicSubscriptionPayload>,
) -> Result<Response> {
    let email = payload.email.trim().to_ascii_lowercase();
    let client_ip = abuse_guard::detect_client_ip(&headers);
    abuse_guard::enforce_public_scope(
        "subscription",
        client_ip.as_deref(),
        Some(&email),
    )?;
    let _ = turnstile::verify_if_enabled(
        &ctx,
        turnstile::TurnstileScope::Subscription,
        payload.turnstile_token.as_deref(),
        client_ip.as_deref(),
    )
    .await?;

    let result = subscriptions::create_public_email_subscription(
        &ctx,
        &email,
        payload.display_name,
        Some(public_subscription_metadata(payload.source)),
    )
    .await?;

    admin_audit::log_event(
        &ctx,
        None,
        if result.requires_confirmation {
            "subscription.public.pending"
        } else {
            "subscription.public.active"
        },
        "subscription",
        Some(result.subscription.id.to_string()),
        Some(result.subscription.target.clone()),
        Some(serde_json::json!({
            "channel_type": result.subscription.channel_type,
            "status": result.subscription.status,
        })),
    )
    .await?;

    format::json(PublicSubscriptionResponse {
        ok: true,
        subscription_id: result.subscription.id,
        status: result.subscription.status,
        requires_confirmation: result.requires_confirmation,
        message: result.message,
    })
}

#[debug_handler]
pub async fn subscribe_browser_push(
    State(ctx): State<AppContext>,
    headers: axum::http::HeaderMap,
    Json(payload): Json<PublicBrowserPushSubscriptionPayload>,
) -> Result<Response> {
    let settings = crate::controllers::site_settings::load_current(&ctx).await?;
    if !crate::services::web_push::is_enabled(&settings) {
        return Err(Error::BadRequest("浏览器推送未启用".to_string()));
    }

    let endpoint = payload
        .subscription
        .get("endpoint")
        .and_then(serde_json::Value::as_str)
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .ok_or_else(|| Error::BadRequest("browser push subscription.endpoint 不能为空".to_string()))?
        .to_string();
    let client_ip = abuse_guard::detect_client_ip(&headers);
    let user_agent = headers
        .get(header::USER_AGENT)
        .and_then(|value| value.to_str().ok())
        .map(str::trim)
        .filter(|value| !value.is_empty())
        .map(ToString::to_string);

    abuse_guard::enforce_public_scope("browser-push-subscription", client_ip.as_deref(), Some(&endpoint))?;
    let _ = turnstile::verify_if_enabled(
        &ctx,
        turnstile::TurnstileScope::Subscription,
        payload.turnstile_token.as_deref(),
        client_ip.as_deref(),
    )
    .await?;

    let result = subscriptions::create_public_web_push_subscription(
        &ctx,
        payload.subscription.clone(),
        Some(public_browser_push_metadata(
            payload.source,
            payload.subscription,
            user_agent,
        )),
    )
    .await?;

    admin_audit::log_event(
        &ctx,
        None,
        "subscription.public.web_push.active",
        "subscription",
        Some(result.subscription.id.to_string()),
        Some(result.subscription.target.clone()),
        Some(serde_json::json!({
            "channel_type": result.subscription.channel_type,
            "status": result.subscription.status,
        })),
    )
    .await?;

    format::json(PublicSubscriptionResponse {
        ok: true,
        subscription_id: result.subscription.id,
        status: result.subscription.status,
        requires_confirmation: false,
        message: result.message,
    })
}

#[debug_handler]
pub async fn confirm(
    State(ctx): State<AppContext>,
    Json(payload): Json<SubscriptionTokenPayload>,
) -> Result<Response> {
    let item = subscriptions::confirm_subscription(&ctx, &payload.token).await?;
    admin_audit::log_event(
        &ctx,
        None,
        "subscription.public.confirm",
        "subscription",
        Some(item.id.to_string()),
        Some(item.target.clone()),
        Some(serde_json::json!({ "channel_type": item.channel_type })),
    )
    .await?;

    format::json(SubscriptionManageResponse {
        ok: true,
        subscription: subscriptions::to_public_subscription_view(&item),
    })
}

#[debug_handler]
pub async fn manage(
    State(ctx): State<AppContext>,
    Query(query): Query<SubscriptionManageQuery>,
) -> Result<Response> {
    let item = subscriptions::get_subscription_by_manage_token(&ctx, &query.token).await?;
    format::json(SubscriptionManageResponse {
        ok: true,
        subscription: subscriptions::to_public_subscription_view(&item),
    })
}

#[debug_handler]
pub async fn update_manage(
    State(ctx): State<AppContext>,
    Json(payload): Json<SubscriptionManageUpdatePayload>,
) -> Result<Response> {
    let item = subscriptions::update_subscription_preferences(
        &ctx,
        &payload.token,
        payload.display_name,
        payload.status,
        payload.filters,
    )
    .await?;

    admin_audit::log_event(
        &ctx,
        None,
        "subscription.public.update",
        "subscription",
        Some(item.id.to_string()),
        Some(item.target.clone()),
        None,
    )
    .await?;

    format::json(SubscriptionManageResponse {
        ok: true,
        subscription: subscriptions::to_public_subscription_view(&item),
    })
}

#[debug_handler]
pub async fn unsubscribe(
    State(ctx): State<AppContext>,
    Json(payload): Json<SubscriptionTokenPayload>,
) -> Result<Response> {
    let item = subscriptions::unsubscribe_subscription(&ctx, &payload.token).await?;
    admin_audit::log_event(
        &ctx,
        None,
        "subscription.public.unsubscribe",
        "subscription",
        Some(item.id.to_string()),
        Some(item.target.clone()),
        None,
    )
    .await?;

    format::json(SubscriptionManageResponse {
        ok: true,
        subscription: subscriptions::to_public_subscription_view(&item),
    })
}

pub fn routes() -> Routes {
    Routes::new()
        .prefix("/api/subscriptions")
        .add("/", post(subscribe))
        .add("/browser-push", post(subscribe_browser_push))
        .add("/confirm", post(confirm))
        .add("/manage", get(manage).patch(update_manage))
        .add("/unsubscribe", post(unsubscribe))
}
