use crate::{ApiResponse, error::ApiError};
use actix_web::{HttpResponse, Result, web};
use models::DateTime;
use serde::Serialize;
use service::AppService;
use service::auth::register::RegisterParams;
use session::Session;
use utoipa::ToSchema;

#[derive(Serialize, ToSchema)]
pub struct RegisterResponse {
    uid: String,
    username: String,
    display_name: Option<String>,
    avatar_url: Option<String>,
    #[schema(ignore)]
    created_at: DateTime,
}

#[utoipa::path(
    post,
    path = "/api/auth/register",
    request_body = RegisterParams,
    responses(
        (status = 401, description = "Unauthorized", body = ApiResponse<ApiError>),
        (status = 200, description = "Registration successful", body = ApiResponse<ApiError>),
        (status = 400, description = "Bad request", body = ApiResponse<ApiError>),
        (status = 409, description = "Username or email already exists", body = ApiResponse<ApiError>),
        (status = 500, description = "Internal server error", body = ApiResponse<ApiError>),
        (status = 404, description = "Not found", body = ApiResponse<ApiError>),
    ),
    tag = "Auth"
)]
pub async fn api_auth_register(
    service: web::Data<AppService>,
    session: Session,
    params: web::Json<RegisterParams>,
) -> Result<HttpResponse, ApiError> {
    let user = service.auth_register(params.into_inner(), &session).await?;
    let payload = RegisterResponse {
        uid: user.uid.to_string(),
        username: user.username,
        display_name: user.display_name,
        avatar_url: user.avatar_url,
        created_at: user.created_at.naive_utc(),
    };
    Ok(ApiResponse::ok(payload).to_response())
}
