import type { Context } from "hono";
import type { Env } from "../types/env";
import { jsonError } from "./http";

type PanelCtx = Context<{ Bindings: Env }>;

/** 管理类接口：X-App-Token 或 Authorization: Bearer <面板令牌> */
export function resolvePanelToken(c: PanelCtx): string {
  const x = (c.req.header("X-App-Token") ?? "").trim();
  if (x) return x;
  const auth = c.req.header("Authorization") ?? "";
  const m = auth.match(/^Bearer\s+(.+)$/i);
  return m ? m[1].trim() : "";
}

export function requirePanelForManagement(c: PanelCtx): Response | null {
  const t = resolvePanelToken(c);
  if (t !== c.env.APP_ACCESS_TOKEN) {
    return jsonError(401, "Invalid app access token");
  }
  return null;
}

/** Cloudflare 代理：面板令牌只能用 X-App-Token（避免与 CF 的 Bearer 冲突） */
export function requirePanelForCfProxy(c: PanelCtx): Response | null {
  const t = (c.req.header("X-App-Token") ?? "").trim();
  if (t !== c.env.APP_ACCESS_TOKEN) {
    return jsonError(
      401,
      "Invalid app access token (use header X-App-Token for /api/cf)",
    );
  }
  return null;
}
