/**
 * Centralized Supabase client
 * Single source of truth for database connections across the monorepo
 * Used by: apps/api, organizations/registry (agent/workflow definitions), packages/core (sessions)
 */

import type { SupabaseClient } from '@supabase/supabase-js'
import type { Database } from '../database.types'

let _supabaseClient: SupabaseClient<Database> | null = null

/**
 * Get Supabase service role client (lazy initialization)
 * Bypasses RLS policies - use with caution, always enforce authorization in application logic
 *
 * @returns Authenticated Supabase client instance
 * @throws Error if SUPABASE_URL or SUPABASE_SERVICE_KEY environment variables are missing
 */
export async function getSupabaseClient(): Promise<SupabaseClient<Database>> {
  if (!_supabaseClient) {
    const { createClient } = await import('@supabase/supabase-js')

    const supabaseUrl = process.env.SUPABASE_URL
    const supabaseServiceKey = process.env.SUPABASE_SERVICE_KEY

    if (!supabaseUrl || !supabaseServiceKey) {
      throw new Error('Missing Supabase environment variables: SUPABASE_URL and SUPABASE_SERVICE_KEY are required')
    }

    _supabaseClient = createClient<Database>(supabaseUrl, supabaseServiceKey, {
      auth: {
        autoRefreshToken: false,
        persistSession: false
      }
    })
  }

  return _supabaseClient
}

/**
 * Synchronous client getter (for backward compatibility)
 * Returns cached client or throws if not initialized
 *
 * @deprecated Use getSupabaseClient() for new code
 * @throws Error if client not initialized - call getSupabaseClient() first
 */
export const supabaseClient = new Proxy({} as SupabaseClient<Database>, {
  get(_target, prop) {
    if (!_supabaseClient) {
      throw new Error(
        'Supabase client not initialized. Call getSupabaseClient() first or use top-level await: ' +
          'const client = await getSupabaseClient()'
      )
    }
    return Reflect.get(_supabaseClient, prop)
  }
})
