use crate::{ApiResponse, error::ApiError};
use actix_web::{HttpResponse, Result, web};
use service::AppService;
use session::Session;

#[utoipa::path(
    post,
    path = "/api/users/me/access-keys",
    request_body = service::user::access_key::CreateAccessKeyParams,
    responses(
        (status = 200, description = "Create access key", body = ApiResponse<service::user::access_key::AccessKeyResponse>),
        (status = 401, description = "Unauthorized"),
),
    tag = "User"
)]
pub async fn create_access_key(
    service: web::Data<AppService>,
    session: Session,
    body: web::Json<service::user::access_key::CreateAccessKeyParams>,
) -> Result<HttpResponse, ApiError> {
    let resp = service
        .user_create_access_key(&session, body.into_inner())
        .await?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[utoipa::path(
    get,
    path = "/api/users/me/access-keys",
    responses(
        (status = 200, description = "List access keys", body = ApiResponse<service::user::access_key::AccessKeyListResponse>),
        (status = 401, description = "Unauthorized"),
),
    tag = "User"
)]
pub async fn list_access_keys(
    service: web::Data<AppService>,
    session: Session,
) -> Result<HttpResponse, ApiError> {
    let resp = service.user_list_access_keys(&session).await?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[utoipa::path(
    delete,
    path = "/api/users/me/access-keys/{access_key_id}",
    params(("access_key_id" = i64, Path)),
    responses(
        (status = 200, description = "Delete access key"),
        (status = 401, description = "Unauthorized"),
        (status = 404, description = "Not found"),
),
    tag = "User"
)]
pub async fn delete_access_key(
    service: web::Data<AppService>,
    session: Session,
    path: web::Path<i64>,
) -> Result<HttpResponse, ApiError> {
    let id = path.into_inner();
    service.user_delete_access_key(&session, id).await?;
    Ok(ApiResponse::ok(serde_json::json!({ "success": true })).to_response())
}
