import type { Hono } from "hono";
import type { Env } from "../types/env";
import { jsonError } from "../lib/http";
import { requirePanelForCfProxy } from "../lib/auth";

/** 透传 Cloudflare API v4 */
export function registerCfProxyRoutes(app: Hono<{ Bindings: Env }>): void {
  app.all("/api/cf/*", async (c) => {
    const denied = requirePanelForCfProxy(c);
    if (denied) return denied;
    const auth = c.req.header("Authorization") ?? "";
    if (!auth.startsWith("Bearer ") || auth.length < 12) {
      return jsonError(
        400,
        "Missing or invalid Cloudflare API token (Authorization: Bearer ...)",
      );
    }

    const url = new URL(c.req.url);
    const rest = url.pathname.replace(/^\/api\/cf/, "") || "/";
    const cfUrl = `https://api.cloudflare.com/client/v4${rest}${url.search}`;

    const headers = new Headers();
    headers.set("Authorization", auth);
    const ct = c.req.header("Content-Type");
    if (ct) headers.set("Content-Type", ct);

    const method = c.req.method;
    let body: BodyInit | undefined;
    if (!["GET", "HEAD"].includes(method)) {
      body = await c.req.arrayBuffer();
    }

    const res = await fetch(cfUrl, { method, headers, body });
    const out = new Response(res.body, { status: res.status });
    const outCt = res.headers.get("Content-Type");
    if (outCt) out.headers.set("Content-Type", outCt);
    return out;
  });
}
