import { createClient, SupabaseClient } from '@supabase/supabase-js'
import type { SupabaseClientConfig } from '../types'

let client: SupabaseClient | null = null

function cfg(): SupabaseClientConfig | undefined {
  return typeof window !== 'undefined' ? window.__APP_CONFIG__?.supabase : undefined
}

/**
 * Returns true when Supabase is configured for this project
 * (both url and publishableKey present in window.__APP_CONFIG__.supabase).
 */
export function isSupabaseConfigured(): boolean {
  const c = cfg()
  return !!(c && c.url && c.publishableKey)
}

/**
 * Get the project schema that all queries are scoped to.
 * Falls back to 'public' when not configured.
 */
export function getProjectSchema(): string {
  return cfg()?.schema || 'public'
}

/**
 * Initialize the Supabase client from window.__APP_CONFIG__.supabase.
 * Returns the client, or null + a console.warn when config is absent/invalid.
 * Idempotent (singleton); never throws.
 */
export function initSupabase(): SupabaseClient | null {
  if (client) return client
  const c = cfg()
  if (!c || !c.url || !c.publishableKey) {
    console.warn('Supabase config not found in __APP_CONFIG__')
    return null
  }
  client = createClient(c.url, c.publishableKey, { db: { schema: c.schema } }) as SupabaseClient
  return client
}

/** Get the initialized Supabase client, or null if not yet initialized. */
export function getSupabase(): SupabaseClient | null {
  return client
}

/** Reset the singleton (useful for tests or re-initialization). */
export function resetSupabase(): void {
  client = null
}
