// ─────────────────────────────────────────────────────────────────────────────
// Supabase client (singleton)
//
// Lazy-init singleton for the Supabase JS client.  The client is created once
// during module evaluation if both env vars are present; `getSupabase()` either
// returns that instance or throws a descriptive error.
// ─────────────────────────────────────────────────────────────────────────────

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

const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL || ""
const supabaseAnonKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || ""

let client: SupabaseClient | null = null

// Initialise eagerly at module load so that subsequent calls are quick,
// provided the environment variables are set.
if (supabaseUrl && supabaseAnonKey) {
  client = createClient(supabaseUrl, supabaseAnonKey)
}

/**
 * Return the singleton Supabase client.
 *
 * @throws  If `NEXT_PUBLIC_SUPABASE_URL` or `NEXT_PUBLIC_SUPABASE_ANON_KEY` are
 *          missing – the client was never created.
 * @returns The initialised `SupabaseClient` instance.
 */
export function getSupabase(): SupabaseClient {
  if (!client) {
    throw new Error(
      "Supabase is not configured. " +
      "Set NEXT_PUBLIC_SUPABASE_URL and NEXT_PUBLIC_SUPABASE_ANON_KEY " +
      "environment variables.",
    )
  }
  return client
}
