/**
 * Route table for the public Platform API (/api/v1, BRD §11). One table drives dispatch, auth scopes and the
 * generated OpenAPI 3 document, so docs never drift from code.
 */
import type { NextRequest } from "next/server";
import type { ZodTypeAny } from "zod";
import type { Ctx } from "@/lib/auth";
import type { ApiScope } from "@/lib/rbac";

export type Handler = (req: NextRequest, ctx: Ctx, params: Record<string, string>) => Promise<unknown>;
export type PublicHandler = (req: NextRequest, params: Record<string, string>) => Promise<unknown>;

export type Route = {
  method: "GET" | "POST" | "PATCH" | "PUT" | "DELETE";
  path: string; // e.g. /contacts/:id
  summary: string;
  tag: string;
  scope?: ApiScope;
  body?: ZodTypeAny;
  handler?: Handler;
  public?: PublicHandler;
  internal?: boolean; // UI-only helper, hidden from OpenAPI
};

export const routes: Route[] = [];
export function route(r: Route) {
  routes.push(r);
}

export function match(method: string, path: string) {
  const segs = path.split("/").filter(Boolean);
  for (const r of routes) {
    if (r.method !== method) continue;
    const rs = r.path.split("/").filter(Boolean);
    if (rs.length !== segs.length) continue;
    const params: Record<string, string> = {};
    let ok = true;
    for (let i = 0; i < rs.length; i++) {
      if (rs[i]!.startsWith(":")) params[rs[i]!.slice(1)] = decodeURIComponent(segs[i]!);
      else if (rs[i] !== segs[i]) { ok = false; break; }
    }
    if (ok) return { route: r, params };
  }
  return null;
}

export function allowedMethods(path: string) {
  const segs = path.split("/").filter(Boolean);
  return routes.filter((r) => {
    const rs = r.path.split("/").filter(Boolean);
    return rs.length === segs.length && rs.every((s, i) => s.startsWith(":") || s === segs[i]);
  }).map((r) => r.method);
}
