/**
 * Registers the `/database/*` HTTP surface onto the Fastify app.
 *
 * Single public entry point (mirrors src/admin/plugin.ts). hub.ts calls
 * registerDatabasePlugin() so the routes are recognized at startup.
 *
 * Register AFTER registerAdminPlugin: it relies on the @fastify/cookie parser
 * and the /auth/feishu/* login routes that the admin plugin adds.
 *
 * The dev login bypass is self-contained in THIS module: the flag is read here
 * (not threaded from hub.ts) and only ever enables the `/database/dev-login`
 * route below. Double-gated: NODE_ENV must not be production AND
 * HUB_DEV_LOGIN_BYPASS must be truthy. Production always requires real Feishu
 * OAuth.
 */
import type { FastifyInstance } from "fastify";
import type { PrismaClient } from "@prisma/client";
import { registerDatabaseRoutes } from "./routes/databaseRoutes.js";

export interface DatabasePluginConfig {
  readonly prisma: PrismaClient;
  readonly sessionSecret: string;
  readonly siloOrganizationSlug: string;
}

const FALSY = new Set(["", "0", "false", "no", "off"]);

export async function registerDatabasePlugin(
  app: FastifyInstance,
  config: DatabasePluginConfig,
): Promise<void> {
  const allowDevLoginBypass =
    process.env["NODE_ENV"] !== "production" &&
    !FALSY.has((process.env["HUB_DEV_LOGIN_BYPASS"] ?? "").trim().toLowerCase());
  if (allowDevLoginBypass) {
    app.log.warn("DEV login bypass enabled: /database/dev-login mints a session without Feishu OAuth");
  }

  await registerDatabaseRoutes(app, {
    prisma: config.prisma,
    sessionSecret: config.sessionSecret,
    siloOrganizationSlug: config.siloOrganizationSlug,
    allowDevLoginBypass,
  });
}
