// Actix-web demo example
// Run with: cargo run --example actix_demo --features actix

#![cfg(feature = "actix")]

use actix_web::{App, HttpServer, Responder, get, post, web};
use anycms_core::{ApiResult, ResultPagination};
use serde::{Deserialize, Serialize};

#[derive(Debug, Serialize, Deserialize)]
struct User {
    id: u32,
    name: String,
    email: String,
}

#[derive(Debug, Serialize, Deserialize)]
struct CreateUserRequest {
    name: String,
    email: String,
}

// Mock user data
async fn get_users() -> Vec<User> {
    vec![
        User {
            id: 1,
            name: "张三".to_string(),
            email: "zhangsan@example.com".to_string(),
        },
        User {
            id: 2,
            name: "李四".to_string(),
            email: "lisi@example.com".to_string(),
        },
        User {
            id: 3,
            name: "王五".to_string(),
            email: "wangwu@example.com".to_string(),
        },
    ]
}

async fn get_user_by_id(id: u32) -> Option<User> {
    let users = get_users().await;
    users.into_iter().find(|u| u.id == id)
}

#[get("/")]
async fn index() -> ApiResult<()> {
    ApiResult::ok()
}

#[get("/users")]
async fn list_users() -> impl Responder {
    let users = get_users().await;
    let pagination = ResultPagination::new(100, 1, 10);

    ApiResult::list(users)
        .with_pagination(pagination)
        .with_extra("total_count", serde_json::json!(100))
        .with_extra("has_more", serde_json::json!(true))
}

#[get("/users/{id}")]
async fn get_user(path: web::Path<u32>) -> impl Responder {
    let user_id = path.into_inner();

    match get_user_by_id(user_id).await {
        Some(user) => ApiResult::value(user),
        None => ApiResult::<User>::fail("用户不存在"),
    }
}

#[post("/users")]
async fn create_user(user_data: web::Json<CreateUserRequest>) -> impl Responder {
    let new_user = User {
        id: 999,
        name: user_data.name.clone(),
        email: user_data.email.clone(),
    };

    ApiResult::value(new_user)
        .with_extra("created_at", serde_json::json!("2024-01-01T00:00:00Z"))
        .with_extra("status", serde_json::json!("active"))
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    println!("🚀 Starting Actix-web demo server...");
    println!("📝 Available endpoints:");
    println!("  GET  /              - Basic success response");
    println!("  GET  /users         - User list with pagination");
    println!("  GET  /users/1       - Get single user");
    println!("  POST /users         - Create user");

    HttpServer::new(|| {
        App::new()
            .service(index)
            .service(list_users)
            .service(get_user)
            .service(create_user)
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await?;

    Ok(())
}
