import { NextResponse } from "next/server";

import { getAppCloudflareEnv } from "../runtime/cloudflare";

interface ApiAccessOptions {
  apiAccessKey?: string;
  authDisabled?: boolean;
}

type ApiAccessResult =
  | { ok: true }
  | { ok: false; response: NextResponse<{ error: string }> };

export function requireApiAccess(
  request: Request,
  options: ApiAccessOptions = {
    apiAccessKey: getConfiguredApiAccessKey(),
    authDisabled: process.env.API_AUTH_DISABLED === "true",
  },
): ApiAccessResult {
  if (options.authDisabled) {
    return { ok: true };
  }

  if (!options.apiAccessKey) {
    return {
      ok: false,
      response: NextResponse.json(
        { error: "API access key is not configured" },
        { status: 401 },
      ),
    };
  }

  const provided = request.headers.get("x-api-key");
  if (provided !== options.apiAccessKey) {
    return {
      ok: false,
      response: NextResponse.json({ error: "Unauthorized" }, { status: 401 }),
    };
  }

  return { ok: true };
}

function getConfiguredApiAccessKey() {
  return getAppCloudflareEnv()?.API_ACCESS_KEY ?? process.env.API_ACCESS_KEY;
}
