use crate::{ApiResponse, error::ApiError};
use actix_web::{HttpResponse, Result, web};
use service::AppService;
use service::auth::email::{EmailChangeRequest, EmailResponse, EmailVerifyRequest};
use session::Session;

#[utoipa::path(
    post,
    path = "/api/auth/email",
    responses(
        (status = 200, description = "Current email address", body = ApiResponse<EmailResponse>),
        (status = 401, description = "Unauthorized"),
    ),
    tag = "Auth"
)]
pub async fn api_email_get(
    service: web::Data<AppService>,
    session: Session,
) -> Result<HttpResponse, ApiError> {
    let email = service.auth_get_email(&session).await?;
    Ok(ApiResponse::ok(email).to_response())
}

#[utoipa::path(
    post,
    path = "/api/auth/email/change",
    request_body = EmailChangeRequest,
    responses(
        (status = 200, description = "Verification email sent", body = ApiResponse<String>),
        (status = 401, description = "Unauthorized or invalid password"),
        (status = 409, description = "Email already in use"),
    ),
    tag = "Auth"
)]
pub async fn api_email_change(
    service: web::Data<AppService>,
    session: Session,
    body: web::Json<EmailChangeRequest>,
) -> Result<HttpResponse, ApiError> {
    service
        .auth_email_change_request(&session, body.into_inner())
        .await?;
    Ok(crate::api_success())
}

#[utoipa::path(
    post,
    path = "/api/auth/email/verify",
    request_body = EmailVerifyRequest,
    responses(
        (status = 200, description = "Email updated successfully", body = ApiResponse<String>),
        (status = 400, description = "Invalid or expired token"),
    ),
    tag = "Auth"
)]
pub async fn api_email_verify(
    service: web::Data<AppService>,
    body: web::Json<EmailVerifyRequest>,
) -> Result<HttpResponse, ApiError> {
    service.auth_email_verify(body.into_inner()).await?;
    Ok(crate::api_success())
}
