import { describe, it, expect, vi, beforeEach } from 'vitest'
import { initSupabase, getSupabase, isSupabaseConfigured, getProjectSchema, resetSupabase } from '../src/lib/supabase'

const createClient = vi.fn((..._a: any[]) => ({ __client: true }))
vi.mock('@supabase/supabase-js', () => ({ createClient: (...a: any[]) => createClient(...a) }))

beforeEach(() => { resetSupabase(); createClient.mockClear(); (window as any).__APP_CONFIG__ = undefined })

describe('lib/supabase', () => {
  it('returns null + warns when no config', () => {
    expect(initSupabase()).toBeNull()
    expect(isSupabaseConfigured()).toBe(false)
  })
  it('creates a schema-scoped client from __APP_CONFIG__.supabase', () => {
    ;(window as any).__APP_CONFIG__ = { supabase: { url: 'https://x.supabase.co', publishableKey: 'sb_publishable_k', schema: 'proj_abc' } }
    const c = initSupabase()
    expect(c).not.toBeNull()
    expect(createClient).toHaveBeenCalledWith('https://x.supabase.co', 'sb_publishable_k', { db: { schema: 'proj_abc' } })
    expect(isSupabaseConfigured()).toBe(true)
    expect(getProjectSchema()).toBe('proj_abc')
    expect(getSupabase()).toBe(c)
  })
  it('is idempotent (singleton)', () => {
    ;(window as any).__APP_CONFIG__ = { supabase: { url: 'https://x.supabase.co', publishableKey: 'k', schema: 's' } }
    initSupabase(); initSupabase()
    expect(createClient).toHaveBeenCalledTimes(1)
  })
  it('returns null when url or key missing', () => {
    ;(window as any).__APP_CONFIG__ = { supabase: { url: '', publishableKey: '', schema: 's' } }
    expect(initSupabase()).toBeNull()
  })
})
