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

let cachedClient: SupabaseClient | null = null

export function getSupabaseClient(): SupabaseClient {
  if (cachedClient) {
    return cachedClient
  }

  const {
    supabase: { url, serviceRoleKey }
  } = useRuntimeConfig()

  if (!url || !serviceRoleKey) {
    throw createError({
      statusCode: 500,
      statusMessage:
        'Supabase credentials are missing. Please set SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY.'
    })
  }

  cachedClient = createClient(url, serviceRoleKey, {
    auth: { persistSession: false },
    db: { schema: 'public' }
  })

  return cachedClient
}
