use axum::{
    extract::{Query, State},
    http::StatusCode,
    routing::get,
    Json, Router,
};

use crate::AppState;
use theseus_core::*;

pub(crate) fn router() -> Router<AppState> {
    Router::new().route("/api/search", get(global_search))
}

#[derive(serde::Deserialize)]
pub(crate) struct SearchQuery {
    q: String,
}

async fn global_search(
    State(state): State<AppState>,
    Query(params): Query<SearchQuery>,
) -> Result<Json<ApiResponse<Vec<SearchResult>>>, StatusCode> {
    if params.q.trim().is_empty() {
        return Err(StatusCode::BAD_REQUEST);
    }
    let results = state
        .db
        .global_search(&params.q)
        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
    Ok(Json(ApiResponse::ok(results)))
}
