//! 用户处理器

use axum::{
    extract::State,
    http::StatusCode,
    response::IntoResponse,
    Json,
};
use std::sync::Arc;

use crate::models::{ApiResponse, UpdateUserRequest, UserResponse};
use crate::services::{auth::{AuthService, UserRepository}, AppState};
use super::{api_error, AuthUser};

/// 获取当前用户信息
pub async fn get_current_user(
    State(state): State<Arc<AppState>>,
    user: AuthUser,
) -> impl IntoResponse {
    let repo = UserRepository::new(&state.db);

    match repo.find_by_id(&user.user_id).await {
        Ok(user_row) => {
            let response: UserResponse = user_row.into();
            (StatusCode::OK, Json(ApiResponse::ok(response))).into_response()
        }
        Err(e) => api_error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
    }
}

/// 更新用户信息
pub async fn update_user(
    State(state): State<Arc<AppState>>,
    user: AuthUser,
    Json(req): Json<UpdateUserRequest>,
) -> impl IntoResponse {
    let repo = UserRepository::new(&state.db);

    // 如果要更新密码，先哈希
    let password_hash = req.password.as_ref().map(|p| {
        let (hash, _) = AuthService::hash_password(p);
        hash
    });

    match repo.update(&user.user_id, req.email.as_deref(), password_hash.as_deref()).await {
        Ok(_) => {
            match repo.find_by_id(&user.user_id).await {
                Ok(user_row) => {
                    let response: UserResponse = user_row.into();
                    (StatusCode::OK, Json(ApiResponse::ok(response))).into_response()
                }
                Err(e) => api_error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
            }
        }
        Err(e) => api_error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
    }
}
