use actix_web::{HttpResponse, web};
use serde::Serialize;
use service::{
    AppService,
    user::sshkey::{CreateUserSshKey, UpdateUserSshKey, UserSshKey},
};
use session::Session;

use crate::error::ApiError;

fn ok_json<T: Serialize>(data: T) -> Result<HttpResponse, ApiError> {
    Ok(HttpResponse::Ok().json(data))
}

fn ok() -> Result<HttpResponse, ApiError> {
    Ok(HttpResponse::Ok().finish())
}

#[utoipa::path(
    get,
    path = "/api/v1/user/ssh-keys",
    responses(
        (status = 200, body = Vec<UserSshKey>)
    ),
    tag = "user"
)]
pub async fn list_ssh_keys(
    service: web::Data<AppService>,
    session: Session,
) -> Result<HttpResponse, ApiError> {
    let keys = service.user_ssh_keys(&session).await?;
    ok_json(keys)
}

#[utoipa::path(
    post,
    path = "/api/v1/user/ssh-keys",
    request_body = CreateUserSshKey,
    responses(
        (status = 200, body = UserSshKey)
    ),
    tag = "user"
)]
pub async fn add_ssh_key(
    service: web::Data<AppService>,
    session: Session,
    body: web::Json<CreateUserSshKey>,
) -> Result<HttpResponse, ApiError> {
    let key = service
        .user_add_ssh_key(&session, body.into_inner())
        .await?;
    ok_json(key)
}

#[utoipa::path(
    put,
    path = "/api/v1/user/ssh-keys/{id}",
    request_body = UpdateUserSshKey,
    responses(
        (status = 200, body = UserSshKey)
    ),
    params(
        ("id" = i64, Path, description = "SSH key ID")
    ),
    tag = "user"
)]
pub async fn update_ssh_key(
    service: web::Data<AppService>,
    session: Session,
    key_id: web::Path<i64>,
    body: web::Json<UpdateUserSshKey>,
) -> Result<HttpResponse, ApiError> {
    let key = service
        .user_update_ssh_key(&session, key_id.into_inner(), body.into_inner())
        .await?;
    ok_json(key)
}

#[utoipa::path(
    delete,
    path = "/api/v1/user/ssh-keys/{id}",
    responses(
        (status = 200)
    ),
    params(
        ("id" = i64, Path, description = "SSH key ID")
    ),
    tag = "user"
)]
pub async fn revoke_ssh_key(
    service: web::Data<AppService>,
    session: Session,
    key_id: web::Path<i64>,
) -> Result<HttpResponse, ApiError> {
    service
        .user_revoke_ssh_key(&session, key_id.into_inner())
        .await?;
    ok()
}
