use actix_web::{web, delete, get, post, HttpResponse};
use sqlx::postgres::PgPool;
use tracing::{debug, info};

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

// GET /api/favorites - 获取收藏列表
#[get("/api/favorites")]
pub async fn get_favorites(
    query: web::Query<serde_json::Value>,
    pool: web::Data<PgPool>,
    claims: web::ReqData<Claims>,
) -> Result<HttpResponse, AppError> {
    let page = query.get("page").and_then(|v| v.as_i64()).unwrap_or(1).max(1) as i32;
    let limit = query.get("limit").and_then(|v| v.as_i64()).unwrap_or(10).clamp(1, 100) as i32;

    debug!("获取收藏列表, 页码: {}, 每页条数: {}", page, limit);

    let response = db::get_favorites_list(pool.get_ref(), claims.user_id, page, limit).await?;

    Ok(HttpResponse::Ok().json(serde_json::json!({
        "success": true,
        "data": response.list,
        "page": page,
        "limit": limit,
        "total": response.total
    })))
}

// POST /api/favorites/{id} - 添加收藏
#[post("/api/favorites/{id}")]
pub async fn add_favorite(
    path: web::Path<i32>,
    pool: web::Data<PgPool>,
    claims: web::ReqData<Claims>,
) -> Result<HttpResponse, AppError> {
    let weather_id = path.into_inner();
    info!("添加收藏, weather_id: {}", weather_id);

    db::set_weather_favorite(pool.get_ref(), weather_id, claims.user_id, true).await?;

    Ok(HttpResponse::Ok().json(serde_json::json!({
        "success": true,
        "message": "已添加收藏"
    })))
}

// DELETE /api/favorites/{id} - 取消收藏
#[delete("/api/favorites/{id}")]
pub async fn remove_favorite(
    path: web::Path<i32>,
    pool: web::Data<PgPool>,
    claims: web::ReqData<Claims>,
) -> Result<HttpResponse, AppError> {
    let weather_id = path.into_inner();
    info!("取消收藏, weather_id: {}", weather_id);

    db::set_weather_favorite(pool.get_ref(), weather_id, claims.user_id, false).await?;

    Ok(HttpResponse::Ok().json(serde_json::json!({
        "success": true,
        "message": "已取消收藏"
    })))
}