import { createBrowserClient as createBrowserSupabase } from '@supabase/ssr';
import { createServerClient as createServerSupabase } from '@supabase/ssr';
import { createClient } from '@supabase/supabase-js';
import type { Database } from './types';

// --- ASA GENERATED START ---
// Canonical Supabase client for entire project.
// All modules (auth-basic, payments-basic, etc.) use this single client.
// Do NOT create additional Supabase clients elsewhere.
// --- ASA GENERATED END ---

// --- USER CODE START ---

/**
 * Browser client — for client components and hooks.
 * Uses ANON key only. Safe for browser.
 */
export function createBrowserClient() {
  return createBrowserSupabase<Database>(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
  );
}

/**
 * Server client — for route handlers, server actions, middleware.
 * Uses ANON key + cookies for authenticated requests.
 */
export function createServerClient(cookieStore: any) {
  return createServerSupabase<Database>(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
    {
      cookies: {
        getAll() {
          return cookieStore.getAll();
        },
        setAll(cookiesToSet: any[]) {
          try {
            cookiesToSet.forEach(({ name, value, options }) =>
              cookieStore.set(name, value, options),
            );
          } catch {
            // Server Component — ignore
          }
        },
      },
    },
  );
}

/**
 * Admin client — for privileged operations that bypass RLS.
 * Uses SERVICE_ROLE key. NEVER import in browser-capable files.
 * asa lint will flag this as a security violation if used in app/ or ui/.
 */
export function createAdminClient() {
  return createClient<Database>(
    process.env.NEXT_PUBLIC_SUPABASE_URL!,
    process.env.SUPABASE_SERVICE_ROLE_KEY!,
    {
      auth: {
        autoRefreshToken: false,
        persistSession: false,
      },
    },
  );
}

// --- USER CODE END ---
