import type { Context } from "hono";
import { env } from "@/lib/env";

const PY_BASE = env.GetString("CHATBOT_PYTHON_BASE_URL");

/**
 * A helper to proxy requests from a Hono controller to the Python Chatbot API.
 * It forwards relevant headers and handles response normalization.
 *
 * @param c - The Hono context.
 * @param path - The API path to call on the Python service (e.g., '/v1/admin-console/chatbot/prompts').
 * @param method - The HTTP method (e.g., 'GET', 'POST').
 * @param query - Optional URL query parameters.
 * @returns The Hono Response object.
 */
export const proxyToPythonApi = async (
  c: Context,
  path: string,
  method: "GET" | "POST" | "PUT" | "DELETE",
  query?: Record<string, string>,
  body?: any,
) => {
  const url = new URL(`${PY_BASE}${path}`);
  if (query) {
    Object.entries(query).forEach(([key, value]) => {
      url.searchParams.set(key, value);
    });
  }

  const cookie = c.req.header("Cookie") ?? "";

  const res = await fetch(url.toString(), {
    method,
    headers: {
      "Content-Type": "application/json",
      ...(cookie ? { Cookie: cookie } : {}),
      "x-admin-email": c.get("adminEmail") ?? "",
    },
    body: body ? JSON.stringify(body) : undefined,
  });

  // Forward the response from the Python service directly
  return new Response(res.body, {
    status: res.status,
    headers: {
      "Content-Type": "application/json",
    },
  });
};
