// Supabase clients. Two flavors:
//
//   - getPublicSupabase()  → anon key, browser-safe. Honors RLS.
//   - getServiceSupabase() → service-role key, server-only. Bypasses RLS.
//
// Use the service client ONLY in server actions / API routes where you
// must mutate data the user's RLS policy would forbid (e.g. webhooks).

import { createClient } from '@supabase/supabase-js';

export function getPublicSupabase() {
  const url = process.env.NEXT_PUBLIC_SUPABASE_URL;
  const anon = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY;
  if (!url || !anon) {
    throw new Error('NEXT_PUBLIC_SUPABASE_URL + NEXT_PUBLIC_SUPABASE_ANON_KEY must be set');
  }
  return createClient(url, anon);
}

export function getServiceSupabase() {
  const url = process.env.NEXT_PUBLIC_SUPABASE_URL;
  const service = process.env.SUPABASE_SERVICE_ROLE_KEY;
  if (!url || !service) {
    throw new Error('NEXT_PUBLIC_SUPABASE_URL + SUPABASE_SERVICE_ROLE_KEY must be set');
  }
  // service role MUST NEVER ship to the browser — we enforce server-only
  // by requiring the env var to be non-public.
  return createClient(url, service, {
    auth: { persistSession: false, autoRefreshToken: false },
  });
}
