import { IS_TEST_BUILD } from "@/ipc/utils/test_utils";
import { getSupabaseClient } from "./supabase_management_client";
import { SUPABASE_SCHEMA_QUERY } from "./supabase_schema_query";

async function getPublishableKey({ projectId }: { projectId: string }) {
  if (IS_TEST_BUILD) {
    return "test-publishable-key";
  }

  const supabase = await getSupabaseClient();
  let keys;
  try {
    keys = await supabase.getProjectApiKeys(projectId);
  } catch (error) {
    throw new Error(
      `Failed to fetch API keys for Supabase project "${projectId}". This could be due to: 1) Invalid project ID, 2) Network connectivity issues, or 3) Supabase API unavailability. Original error: ${error instanceof Error ? error.message : String(error)}`,
    );
  }
  if (!keys) {
    throw new Error("No keys found for Supabase project " + projectId);
  }
  const publishableKey = keys.find(
    (key) =>
      (key as any)["name"] === "anon" || (key as any)["type"] === "publishable",
  );

  if (!publishableKey) {
    throw new Error(
      "No publishable key found for project. Make sure you are connected to the correct Supabase account and project. See https://dyad.sh/docs/integrations/supabase#no-publishable-keys",
    );
  }
  return publishableKey.api_key;
}
export const getSupabaseClientCode = async function ({
  projectId,
}: {
  projectId: string;
}) {
  const publishableKey = await getPublishableKey({ projectId });
  return `
// This file is automatically generated. Do not edit it directly.
import { createClient } from '@supabase/supabase-js';

const SUPABASE_URL = "https://${projectId}.supabase.co";
const SUPABASE_PUBLISHABLE_KEY = "${publishableKey}";

// Import the supabase client like this:
// import { supabase } from "@/integrations/supabase/client";

export const supabase = createClient(SUPABASE_URL, SUPABASE_PUBLISHABLE_KEY);`;
};

export async function getSupabaseContext({
  supabaseProjectId,
}: {
  supabaseProjectId: string;
}) {
  if (IS_TEST_BUILD) {
    if (supabaseProjectId === "test-branch-project-id") {
      return "1234".repeat(200_000);
    }
    return "[[TEST_BUILD_SUPABASE_CONTEXT]]";
  }

  const supabase = await getSupabaseClient();
  const publishableKey = await getPublishableKey({
    projectId: supabaseProjectId,
  });
  const schema = await supabase.runQuery(
    supabaseProjectId,
    SUPABASE_SCHEMA_QUERY,
  );

  const secrets = await supabase.getSecrets(supabaseProjectId);
  const secretNames = secrets?.map((secret) => secret.name);

  // TODO: include EDGE FUNCTIONS and SECRETS!

  const context = `
  # Supabase Context

  ## Supabase Project ID
  ${supabaseProjectId}

  ## Publishable key (aka anon key)
  ${publishableKey}

  ## Secret names (environmental variables)
  ${JSON.stringify(secretNames)}

  ## Schema
  ${JSON.stringify(schema)}
  `;

  return context;
}
