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

// Use PUBLIC_ prefixed variables for client-side, fallback to server-side for SSR
const supabaseUrl = import.meta.env.PUBLIC_SUPABASE_URL || import.meta.env.SUPABASE_URL
const supabaseAnonKey = import.meta.env.PUBLIC_SUPABASE_ANON_KEY || import.meta.env.SUPABASE_ANON_KEY

if (!supabaseUrl || !supabaseAnonKey) {
  throw new Error('Missing required Supabase environment variables. Make sure SUPABASE_URL and SUPABASE_ANON_KEY are set.')
}

export const supabase = createClient<Database>(supabaseUrl, supabaseAnonKey, {
  auth: {
    flowType: 'pkce',
    autoRefreshToken: true,
    persistSession: true,
    detectSessionInUrl: false, // disable URL-based session detection to avoid SSR redirect loops
    cookieOptions: {
      secure: false,              // localhost is non-HTTPS in Docker
      sameSite: 'lax',            // allow cross-site cookie on navigation
      path: '/',                  // root-wide access
      httpOnly: true,             // JS-inaccessible for security
    },
  }
})

// Service role client for server-side operations that need to bypass RLS
const supabaseServiceRoleKey = import.meta.env.SUPABASE_SERVICE_ROLE_KEY || import.meta.env.SUPABASE_SERVICE_KEY

let supabaseAdmin: ReturnType<typeof createClient<Database>> | null = null

if (supabaseServiceRoleKey) {
  supabaseAdmin = createClient<Database>(supabaseUrl, supabaseServiceRoleKey)
}

export { supabaseAdmin }

