use actix_web::{HttpResponse, Responder, Scope, get, web};
use sea_orm::sea_query::extension::postgres::PgExpr;
use sea_orm::sea_query::Expr;
use sea_orm::{EntityTrait, QueryFilter, QueryOrder};
use serde::{Deserialize, Serialize};
use uuid::Uuid;

use crate::app_data::AppData;
use crate::entity::user;
use crate::error::ApiError;
use crate::middleware::auth::AuthUser;

#[derive(Debug, Deserialize)]
pub struct SearchQuery {
    pub query: Option<String>,
}

#[derive(Debug, Serialize)]
pub struct UserResponse {
    pub id: Uuid,
    pub username: String,
    pub avatar: Option<String>,
}

#[get("")]
async fn search_users(
    app_data: web::Data<AppData>,
    _auth: AuthUser,
    query: web::Query<SearchQuery>,
) -> Result<impl Responder, ApiError> {
    let mut q = user::Entity::find();

    if let Some(search) = &query.query {
        let search = search.trim();
        if !search.is_empty() {
            // 使用 ILIKE 进行不区分大小写的搜索（PostgreSQL）
            let pattern = format!("%{}%", search);
            q = q.filter(
                Expr::col((user::Entity, user::Column::Username))
                    .ilike(&pattern)
            );
        }
    }

    let users = q
        .order_by_asc(user::Column::Username)
        .all(&app_data.db)
        .await?;

    let result: Vec<UserResponse> = users
        .into_iter()
        .map(|u| UserResponse {
            id: u.id,
            username: u.username,
            avatar: u.avatar,
        })
        .collect();

    Ok(HttpResponse::Ok().json(result))
}

pub fn routes() -> Scope {
    web::scope("/api/users").service(search_users)
}
