use actix_web::{HttpResponse, Result, web};
use service::error::AppError;
use service::AppService;
use session::Session;

use crate::{error::ApiError, ApiResponse};

#[derive(serde::Serialize, utoipa::ToSchema)]
pub struct VapidKeyResponse {
    pub public_key: String,
}

#[utoipa::path(
    get,
    path = "/api/users/me/notifications/push/vapid-key",
    responses(
        (status = 200, description = "Get VAPID public key for push subscription", body = ApiResponse<VapidKeyResponse>),
        (status = 503, description = "Push notifications not configured"),
    ),
    tag = "User"
)]
pub async fn get_vapid_public_key(
    service: web::Data<AppService>,
) -> Result<HttpResponse, ApiError> {
    let public_key = service
        .config
        .vapid_public_key();
    let public_key = match public_key {
        Some(k) => k,
        None => {
            let err: AppError = AppError::InternalError;
            return Err(err.into());
        }
    };
    Ok(ApiResponse::ok(VapidKeyResponse { public_key }).to_response())
}

#[utoipa::path(
    delete,
    path = "/api/users/me/notifications/push/subscription",
    responses(
        (status = 200, description = "Unsubscribe from push notifications", body = ApiResponse<serde_json::Value>),
        (status = 401, description = "Unauthorized"),
    ),
    tag = "User"
)]
pub async fn unsubscribe_push(
    service: web::Data<AppService>,
    session: Session,
) -> Result<HttpResponse, ApiError> {
    service.user_unsubscribe_push(&session).await?;
    Ok(ApiResponse::ok(serde_json::json!({ "success": true })).to_response())
}

#[utoipa::path(
    get,
    path = "/api/users/me/notifications/preferences",
    responses(
        (status = 200, description = "Get notification preferences", body = ApiResponse<service::user::notification::NotificationPreferencesResponse>),
        (status = 401, description = "Unauthorized"),
),
    tag = "User"
)]
pub async fn get_notification_preferences(
    service: web::Data<AppService>,
    session: Session,
) -> Result<HttpResponse, ApiError> {
    let resp = service.user_get_notification_preferences(&session).await?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[utoipa::path(
    patch,
    path = "/api/users/me/notifications/preferences",
    request_body = service::user::notification::NotificationPreferencesParams,
    responses(
        (status = 200, description = "Update notification preferences", body = ApiResponse<service::user::notification::NotificationPreferencesResponse>),
        (status = 401, description = "Unauthorized"),
),
    tag = "User"
)]
pub async fn update_notification_preferences(
    service: web::Data<AppService>,
    session: Session,
    body: web::Json<service::user::notification::NotificationPreferencesParams>,
) -> Result<HttpResponse, ApiError> {
    let resp = service
        .user_update_notification_preferences(&session, body.into_inner())
        .await?;
    Ok(ApiResponse::ok(resp).to_response())
}
