import type { Hono } from "hono";
import type { Env } from "../types/env";
import { SERVICE, API_VERSION } from "../lib/constants";
import { requirePanelForManagement } from "../lib/auth";

/** API 目录、健康检查、令牌校验 */
export function registerMetaRoutes(app: Hono<{ Bindings: Env }>): void {
  app.get("/api", (c) => {
    const url = new URL(c.req.url);
    const origin = url.origin;
    return c.json({
      service: SERVICE,
      version: API_VERSION,
      docs: {
        repository_file: "domainflare API调用文档.md",
        note: "面板 HTTP API 说明见仓库内该文档；部署根路径即下方 base。",
      },
      base: `${origin}/api`,
      health: `${origin}/api/health`,
      auth: {
        management:
          "管理接口（账号、校验、及非 cf 代理）可使用 X-App-Token 或 Authorization: Bearer <APP_ACCESS_TOKEN>",
        cloudflare_proxy:
          "/api/cf/* 须同时带 X-App-Token: <APP_ACCESS_TOKEN> 与 Authorization: Bearer <Cloudflare API Token>",
      },
      routes: [
        {
          method: "GET",
          path: "/api/health",
          auth: false,
          description: "健康检查，用于探活",
        },
        {
          method: "GET",
          path: "/api",
          auth: false,
          description: "返回本 API 目录（当前 JSON）",
        },
        {
          method: "GET",
          path: "/api/verify",
          auth: true,
          description: "校验面板访问令牌是否有效",
        },
        {
          method: "GET",
          path: "/api/accounts",
          auth: true,
          description: "列出 D1 中保存的 Cloudflare 账号（响应含 api token）",
        },
        {
          method: "POST",
          path: "/api/accounts",
          auth: true,
          body: { name: "string 可选", token: "string 必填 Cloudflare API Token" },
          description: "新增账号",
        },
        {
          method: "PATCH",
          path: "/api/accounts/:id",
          auth: true,
          body: { name: "string 可选", token: "string 可选" },
          description: "更新账号名称或 Token",
        },
        {
          method: "DELETE",
          path: "/api/accounts/:id",
          auth: true,
          description: "删除账号",
        },
        {
          method: "*",
          path: "/api/cf/…",
          auth: "X-App-Token + Authorization: Bearer <CF_TOKEN>",
          description:
            "透传至 https://api.cloudflare.com/client/v4/…，方法与正文原样转发",
        },
      ],
    });
  });

  app.get("/api/health", (c) =>
    c.json({
      ok: true,
      service: SERVICE,
      version: API_VERSION,
      time: new Date().toISOString(),
    }),
  );

  app.get("/api/verify", (c) => {
    const denied = requirePanelForManagement(c);
    if (denied) return denied;
    return c.json({ ok: true });
  });
}
