use axum::extract::{Query, State};
use axum::routing::get;
use axum::{Json, Router};
use serde::Deserialize;

use crate::app::AppState;
use crate::domain::tag::Tag;
use crate::error::AppResult;
use crate::repo;

pub fn routes() -> Router<AppState> {
    Router::new().route("/tags", get(list))
}

#[derive(Debug, Deserialize)]
pub struct ListParams {
    #[serde(default)]
    pub search: Option<String>,
    #[serde(default = "default_limit")]
    pub limit: i64,
}

fn default_limit() -> i64 {
    10
}

async fn list(
    State(state): State<AppState>,
    Query(params): Query<ListParams>,
) -> AppResult<Json<Vec<Tag>>> {
    let limit = params.limit.clamp(1, 50);
    let search = params.search.as_deref().and_then(|s| {
        let t = s.trim();
        if t.is_empty() { None } else { Some(t) }
    });
    Ok(Json(repo::tag::list(&state.db, search, limit).await?))
}
