use actix_web::{HttpResponse, web};
use serde::Serialize;
use service::{
    AppService,
    user::access_token::{
        CreateUserAccessToken, CreatedUserAccessToken, UpdateUserAccessToken,
        UserAccessToken,
    },
};
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/access-tokens",
    responses(
        (status = 200, body = Vec<UserAccessToken>)
    ),
    tag = "user"
)]
pub async fn list_access_tokens(
    service: web::Data<AppService>,
    session: Session,
) -> Result<HttpResponse, ApiError> {
    let tokens = service.user_access_tokens(&session).await?;
    ok_json(tokens)
}

#[utoipa::path(
    post,
    path = "/api/v1/user/access-tokens",
    request_body = CreateUserAccessToken,
    responses(
        (status = 200, body = CreatedUserAccessToken)
    ),
    tag = "user"
)]
pub async fn create_access_token(
    service: web::Data<AppService>,
    session: Session,
    body: web::Json<CreateUserAccessToken>,
) -> Result<HttpResponse, ApiError> {
    let token = service
        .user_create_access_token(&session, body.into_inner())
        .await?;
    ok_json(token)
}

#[utoipa::path(
    put,
    path = "/api/v1/user/access-tokens/{id}",
    request_body = UpdateUserAccessToken,
    responses(
        (status = 200, body = UserAccessToken)
    ),
    params(
        ("id" = i64, Path, description = "Access token ID")
    ),
    tag = "user"
)]
pub async fn update_access_token(
    service: web::Data<AppService>,
    session: Session,
    token_id: web::Path<i64>,
    body: web::Json<UpdateUserAccessToken>,
) -> Result<HttpResponse, ApiError> {
    let token = service
        .user_update_access_token(
            &session,
            token_id.into_inner(),
            body.into_inner(),
        )
        .await?;
    ok_json(token)
}

#[utoipa::path(
    delete,
    path = "/api/v1/user/access-tokens/{id}",
    responses(
        (status = 200)
    ),
    params(
        ("id" = i64, Path, description = "Access token ID")
    ),
    tag = "user"
)]
pub async fn revoke_access_token(
    service: web::Data<AppService>,
    session: Session,
    token_id: web::Path<i64>,
) -> Result<HttpResponse, ApiError> {
    service
        .user_revoke_access_token(&session, token_id.into_inner())
        .await?;
    ok()
}
