use actix_web::{web, get, put, HttpResponse};
use sqlx::postgres::PgPool;
use tracing::info;
use serde::Deserialize;

use crate::db;
use crate::error::AppError;
use crate::models::Claims;

#[get("/api/user/profile")]
pub async fn get_current_user_profile(
    pool: web::Data<PgPool>,
    claims: web::ReqData<Claims>,
) -> Result<HttpResponse, AppError> {
    let user_id = claims.user_id;
    info!("获取当前用户信息, 用户ID: {}", user_id);

    let user = db::get_user_by_id(pool.get_ref(), user_id).await?;
    let is_paid_active = user.is_paid && 
        (user.paid_expires_at.is_none() || user.paid_expires_at.unwrap() > chrono::Utc::now());
    
    Ok(HttpResponse::Ok().json(serde_json::json!({
        "success": true,
        "data": {
            "id": user.id,
            "name": user.name,
            "nickname": user.nickname,
            "avatarUrl": user.avatar_url,
            "is_paid": user.is_paid,
            "is_paid_active": is_paid_active,
            "is_admin": user.is_admin,
            "paid_expires_at": user.paid_expires_at
        }
    })))
}

#[derive(Debug, Deserialize)]
pub struct SaveUserProfileRequest {
    pub nickname: Option<String>,
    pub avatar_url: Option<String>,
}

#[put("/api/user/profile")]
pub async fn save_user_profile(
    pool: web::Data<PgPool>,
    claims: web::ReqData<Claims>,
    body: web::Json<SaveUserProfileRequest>,
) -> Result<HttpResponse, AppError> {
    let user_id = claims.user_id;
    info!("保存用户信息, 用户ID: {}", user_id);

    db::update_user_profile(pool.get_ref(), user_id, &body.nickname, &body.avatar_url).await?;
    Ok(HttpResponse::Ok().json(serde_json::json!({
        "success": true
    })))
}
