use crate::ApiResponse;
use crate::error::ApiError;
use actix_web::{HttpResponse, Result, web};
use service::AppService;
use service::search::{GlobalMessageSearchQuery, GlobalMessageSearchResponse, SearchQuery, SearchResponse};
use session::Session;

#[utoipa::path(
    get,
    path = "/api/search",
    params(
        ("q" = String, Query, description = "Search keyword", min_length = 1, max_length = 200),
        ("type" = Option<String>, Query, description = "Comma-separated types: projects,repos,issues,users. Default: all"),
        ("page" = Option<u32>, Query, description = "Page number, default 1"),
        ("per_page" = Option<u32>, Query, description = "Results per page, default 20, max 100"),
    ),
    responses(
        (status = 200, description = "Search results", body = ApiResponse<SearchResponse>),
        (status = 400, description = "Bad request"),
        (status = 401, description = "Unauthorized"),
    ),
    tag = "Search"
)]
pub async fn search(
    service: web::Data<AppService>,
    session: Session,
    query: web::Query<SearchQuery>,
) -> Result<HttpResponse, ApiError> {
    let resp = service.search(&session, query.into_inner()).await?;
    Ok(ApiResponse::ok(resp).to_response())
}

#[utoipa::path(
    get,
    path = "/api/search/messages",
    params(
        ("q" = String, Query, description = "Search keyword", min_length = 1, max_length = 200),
        ("page" = Option<u32>, Query, description = "Page number, default 1"),
        ("per_page" = Option<u32>, Query, description = "Results per page, default 20, max 100"),
    ),
    responses(
        (status = 200, description = "Message search results across all accessible rooms", body = ApiResponse<GlobalMessageSearchResponse>),
        (status = 400, description = "Bad request"),
        (status = 401, description = "Unauthorized"),
    ),
    tag = "Search"
)]
pub async fn search_messages(
    service: web::Data<AppService>,
    session: Session,
    query: web::Query<GlobalMessageSearchQuery>,
) -> Result<HttpResponse, ApiError> {
    let resp = service.global_message_search(&session, query.into_inner()).await?;
    Ok(ApiResponse::ok(resp).to_response())
}
