import { getSupabaseClient } from "./supabase_management_client";
import { SUPABASE_SCHEMA_QUERY } from "./supabase_schema_query";

async function getPublishableKey({ projectId }: { projectId: string }) {
  const supabase = await getSupabaseClient();
  const keys = await supabase.getProjectApiKeys(projectId);
  if (!keys) {
    throw new Error("No keys found for project");
  }
  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");
  }
  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;
}) {
  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;
}
