use actix_web::{HttpResponse, web};
use serde::Serialize;
use service::{
    AppService,
    auth::totp::{
        Disable2FAParams, Enable2FAResponse, Get2FAStatusResponse,
        Verify2FAParams,
    },
};
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(
    post,
    path = "/api/v1/auth/2fa/enable",
    responses((status = 200, body = Enable2FAResponse)),
    tag = "auth"
)]
pub async fn enable_2fa(
    session: Session,
    service: web::Data<AppService>,
) -> Result<HttpResponse, ApiError> {
    let result = service.auth_2fa_enable(&session).await?;
    ok_json(result)
}

#[utoipa::path(
    post,
    path = "/api/v1/auth/2fa/verify",
    request_body = Verify2FAParams,
    responses((status = 200)),
    tag = "auth"
)]
pub async fn verify_2fa(
    session: Session,
    params: web::Json<Verify2FAParams>,
    service: web::Data<AppService>,
) -> Result<HttpResponse, ApiError> {
    service
        .auth_2fa_verify_and_enable(&session, params.into_inner())
        .await?;
    ok()
}

#[utoipa::path(
    delete,
    path = "/api/v1/auth/2fa",
    request_body = Disable2FAParams,
    responses((status = 200)),
    tag = "auth"
)]
pub async fn disable_2fa(
    session: Session,
    params: web::Json<Disable2FAParams>,
    service: web::Data<AppService>,
) -> Result<HttpResponse, ApiError> {
    service
        .auth_2fa_disable(&session, params.into_inner())
        .await?;
    ok()
}

#[utoipa::path(
    get,
    path = "/api/v1/auth/2fa",
    responses((status = 200, body = Get2FAStatusResponse)),
    tag = "auth"
)]
pub async fn status_2fa(
    session: Session,
    service: web::Data<AppService>,
) -> Result<HttpResponse, ApiError> {
    let result = service.auth_2fa_status(&session).await?;
    ok_json(result)
}

#[utoipa::path(
    post,
    path = "/api/v1/auth/2fa/backup-codes",
    request_body = String,
    responses((status = 200)),
    tag = "auth"
)]
pub async fn regenerate_backup_codes(
    session: Session,
    params: web::Json<String>,
    service: web::Data<AppService>,
) -> Result<HttpResponse, ApiError> {
    let result = service
        .auth_2fa_regenerate_backup_codes(&session, params.into_inner())
        .await?;
    ok_json(result)
}
