use axum::{
    Router,
    extract::{Path, State},
    response::Redirect,
    routing::{get, post},
};
use axum_extra::routing::RouterExt as _;
use serde::Deserialize;
use uuid::Uuid;

use crate::{Settings, app::App};

use super::relations_single;

mod add_table_handler;
mod nav_handler;

#[derive(Clone, Debug, Deserialize)]
struct PathParams {
    workspace_id: Uuid,
}

pub(super) fn new_router() -> Router<App> {
    Router::<App>::new()
        .route_with_tsr(
            "/{workspace_id}",
            get(
                |State(Settings { root_path, .. }): State<Settings>,
                 Path(PathParams { workspace_id }): Path<PathParams>| async move {
                    Redirect::to(&format!(
                        "{root_path}/w/{workspace_id}/nav/",
                        workspace_id = workspace_id.simple()
                    ))
                },
            ),
        )
        .route("/{workspace_id}/add-table", post(add_table_handler::post))
        .route_with_tsr("/{workspace_id}/nav/", get(nav_handler::get))
        .nest(
            "/{workspace_id}/r/{rel_oid}",
            relations_single::new_router(),
        )
}
