import { createClient } from "@supabase/supabase-js";
import type { SupabaseCredentials } from "./supabase.js";

export type Column = {
  column_name: string;
  data_type: string;
  default?: string;
  is_nullable?: boolean;
};

export type Constraint = {
  constraint_type?: string;
  type?: string;
  constraint_name?: string;
  name?: string;
  columns?: string[];
  column_names?: string[];
  constrained_columns?: string[];
  foreign_table?: string;
  referenced_table?: string;
  foreign_table_name?: string;
  foreign_table_schema?: string;
  referenced_schema?: string;
  schema?: string;
  foreign_columns?: string[];
  referenced_columns?: string[];
  on_delete?: string;
  delete_rule?: string;
  delete?: string;
  on_update?: string;
  update_rule?: string;
  update?: string;
};

export type Table = {
  table_name: string;
  table_schema?: string;
  table_type?: string;
  columns: Column[];
  constraints?: Constraint[] | Constraint;
};

export type Extension = {
  name: string;
  version: string;
};

export type SchemaJson = {
  schema?: Table[];
  extensions?: Extension[];
};

export const normalizeSchemaJson = (value: SchemaJson | SchemaJson[]): SchemaJson => {
  if (Array.isArray(value)) {
    return value[0];
  }
  return value;
};

export const fetchSchemaJson = async (
  credentials: SupabaseCredentials,
): Promise<SchemaJson | SchemaJson[]> => {
  const client = createClient(credentials.url, credentials.anonKey);
  const { data, error } = await client.rpc("get_full_schema_json", {});
  if (error) {
    throw new Error(error.message ?? "failed to fetch schema");
  }
  return data;
};
