//! API route definitions.
//!
//! This module contains all REST API endpoints organized by service.

pub mod compiler;
pub mod dex;
pub mod health;
pub mod ibc;
pub mod rpc;
pub mod storage;
pub mod wallet;
pub mod zk;

use axum::Router;
use std::sync::Arc;

use crate::config::GatewayConfig;
use crate::websocket::WebSocketState;

/// Application state shared across all routes.
#[derive(Clone)]
pub struct AppState {
    /// Gateway configuration
    pub config: Arc<GatewayConfig>,
    /// WebSocket state for real-time event channels
    pub websocket: Arc<WebSocketState>,
}

impl AppState {
    /// Create new application state.
    pub fn new(config: GatewayConfig) -> Self {
        Self {
            config: Arc::new(config),
            websocket: Arc::new(WebSocketState::new()),
        }
    }

    /// Create with custom WebSocket state.
    pub fn with_websocket(config: GatewayConfig, websocket: WebSocketState) -> Self {
        Self {
            config: Arc::new(config),
            websocket: Arc::new(websocket),
        }
    }
}

/// Build the main API router with all service routes.
pub fn build_router(state: AppState) -> Router {
    Router::new()
        // Health & status endpoints (no auth required)
        .merge(health::router())
        // API version information
        .merge(crate::versioning::router())
        // WebSocket endpoints for real-time updates
        .merge(crate::websocket::router())
        // Versioned API routes
        .nest("/v1", build_v1_router())
        // Future: .nest("/v2", build_v2_router()) for preview API
        .with_state(state)
}

/// Build the v1 API router.
fn build_v1_router() -> Router<AppState> {
    Router::new()
        .nest("/wallet", wallet::router())
        .nest("/rpc", rpc::router())
        .nest("/storage", storage::router())
        .nest("/dex", dex::router())
        .nest("/ibc", ibc::router())
        .nest("/zk", zk::router())
        .nest("/compiler", compiler::router())
}
