import { cleanText } from "./text";

export function corsHeaders(): Record<string, string> {
  return {
    "access-control-allow-origin": "*",
    "access-control-allow-methods": "GET, POST, PUT, DELETE, OPTIONS",
    "access-control-allow-headers": "*"
  };
}

export function jsonResponse(
  data: unknown,
  status = 200,
  extraHeaders: Record<string, string> = {}
): Response {
  return new Response(JSON.stringify(data, null, 2), {
    status,
    headers: {
      "content-type": "application/json; charset=UTF-8",
      ...corsHeaders(),
      ...extraHeaders
    }
  });
}

export async function readBody(request: Request): Promise<Record<string, unknown>> {
  const type = request.headers.get("content-type") || "";
  if (type.includes("application/json")) {
    try {
      return (await request.json()) as Record<string, unknown>;
    } catch {
      return {};
    }
  }

  if (
    type.includes("multipart/form-data") ||
    type.includes("application/x-www-form-urlencoded")
  ) {
    const form = await request.formData();
    const data: Record<string, unknown> = {};
    for (const [key, value] of form.entries()) {
      data[key] = value;
    }
    return data;
  }

  return {};
}

export function unauthorized(): Response {
  return new Response("Authentication required", {
    status: 401,
    headers: {
      "content-type": "text/plain; charset=UTF-8"
    }
  });
}

/** Basic Auth / Cookie 中的密码校验用原始字符串 */
export function getAdminPassword(env: Pick<Env, "ADMIN_PASSWORD">): string {
  return cleanText(env.ADMIN_PASSWORD);
}
