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_service_credential_handler;
mod add_table_handler;
mod grant_workspace_privilege_handler;
mod nav_handler;
mod service_credentials_handler;
mod settings_handler;
mod update_name_handler;
mod update_rel_privileges_handler;
mod update_service_cred_permissions_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_with_tsr("/{workspace_id}/settings/", get(settings_handler::get))
        .route(
            "/{workspace_id}/settings/update-name",
            post(update_name_handler::post),
        )
        .route(
            "/{workspace_id}/settings/grant-workspace-privilege",
            post(grant_workspace_privilege_handler::post),
        )
        // TODO: Standardize naming of "permissions" vs. "privileges".
        .route(
            "/{workspace_id}/settings/update-rel-privileges",
            post(update_rel_privileges_handler::post),
        )
        .route(
            "/{workspace_id}/service-credentials/add-service-credential",
            post(add_service_credential_handler::post),
        )
        .route("/{workspace_id}/add-table", post(add_table_handler::post))
        .route_with_tsr("/{workspace_id}/nav/", get(nav_handler::get))
        .route_with_tsr(
            "/{workspace_id}/service-credentials/",
            get(service_credentials_handler::get),
        )
        .route(
            "/{workspace_id}/service-credentials/{service_cred_id}/update-permissions",
            post(update_service_cred_permissions_handler::post),
        )
        .nest(
            "/{workspace_id}/r/{rel_oid}",
            relations_single::new_router(),
        )
}
