import cookie from "@fastify/cookie";
import multipart from "@fastify/multipart";
import rateLimit from "@fastify/rate-limit";
import Fastify, { type FastifyInstance, type RouteOptions } from "fastify";
import { randomUUID } from "node:crypto";
import { env } from "../config/env.js";
import { pool, query } from "../core/db/db.js";
import { DomainError } from "../core/http/errors.js";
import { setAuthPort } from "../core/http/route.js";
import { accessFor } from "../modules/access/index.js";
import { sessionUser } from "../modules/identity/index.js";
import { modules } from "./moduleRegistry.js";
import { registerErrorHandler } from "./plugins/error-handler.js";

export async function buildApp(options: { logger?: boolean; onRoute?: (route: RouteOptions) => void; rateLimit?: boolean } = {}): Promise<FastifyInstance> {
  const app = Fastify({ logger: options.logger ?? true, genReqId: () => `req_${randomUUID()}`, bodyLimit: 2_097_152, trustProxy: env.TRUST_PROXY === "true" });
  if (options.onRoute) app.addHook("onRoute", options.onRoute);
  registerErrorHandler(app);
  setAuthPort({ user: sessionUser, access: accessFor });
  await app.register(cookie);
  await app.register(multipart, { limits: { fileSize: 25 * 1024 * 1024, files: 10, fields: 40 } });
  if (options.rateLimit !== false) await app.register(rateLimit, { max: 600, timeWindow: "1 minute", errorResponseBuilder: () => new DomainError(429, "RATE_LIMITED", "Too many requests. Wait a minute and try again.") });
  if (env.MIRROR_MODE === "on") {
    // Signing in and out stays possible; every other change would be lost at the next nightly rebuild from V1.
    const open = /^\/api\/v2\/auth\/(login|logout|2fa\/(verify|resend)|demo(\/\d+)?)$/;
    app.addHook("onRequest", async (req) => {
      if (!["GET", "HEAD", "OPTIONS"].includes(req.method) && !open.test(req.url.split("?")[0]!)) throw new DomainError(423, "READ_ONLY_MIRROR", "This is a read-only copy of V1, rebuilt every night. Make changes in V1.");
    });
  }
  app.addHook("onSend", async (_req, reply) => { reply.header("x-content-type-options", "nosniff").header("referrer-policy", "same-origin").header("cache-control", "no-store"); });
  app.get("/health/live", { config: { v1: ["GET /api/health"] } }, async () => ({ status: "ok" }));
  app.get("/health/ready", { config: { v1: ["GET /api/health/db"] } }, async (_req, reply) => {
    try {
      await query(pool, "SELECT 1");
      return { status: "ok" };
    } catch (error) {
      app.log.error({ err: error }, "database unreachable");
      return reply.code(503).send({ status: "database unreachable" });
    }
  });
  for (const module of modules) await app.register(module.routes, { prefix: "/api/v2" });
  return app;
}
