use actix_web::{HttpResponse, web};
use serde::Serialize;
use service::{
    AppService,
    auth::email::{EmailChangeRequest, EmailResponse, EmailVerifyRequest},
};
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/auth/email",
    responses((status = 200, body = EmailResponse)),
    tag = "auth"
)]
pub async fn get_email(
    session: Session,
    service: web::Data<AppService>,
) -> Result<HttpResponse, ApiError> {
    let result = service.auth_get_email(&session).await?;
    ok_json(result)
}

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

#[utoipa::path(
    post,
    path = "/api/v1/auth/email/verify",
    request_body = EmailVerifyRequest,
    responses((status = 200)),
    tag = "auth"
)]
pub async fn email_verify(
    params: web::Json<EmailVerifyRequest>,
    service: web::Data<AppService>,
) -> Result<HttpResponse, ApiError> {
    service.auth_email_verify(params.into_inner()).await?;
    ok()
}
