-- =====================================================
-- RLS POLICIES FOR platform_settings TABLE
-- =====================================================
-- This fixes the empty JSON response when non-admin users
-- try to access branding settings (logo, favicon, colors)
-- =====================================================

-- Step 1: Enable RLS on platform_settings (if not already enabled)
ALTER TABLE platform_settings ENABLE ROW LEVEL SECURITY;

-- Step 2: Drop existing policies (if any)
DROP POLICY IF EXISTS "Public can view platform settings" ON platform_settings;
DROP POLICY IF EXISTS "Authenticated can view platform settings" ON platform_settings;
DROP POLICY IF EXISTS "Admins can update platform settings" ON platform_settings;
DROP POLICY IF EXISTS "Admins can insert platform settings" ON platform_settings;
DROP POLICY IF EXISTS "Admins can delete platform settings" ON platform_settings;

-- Step 3: Create policies

-- Policy 1: Allow ANYONE (including public) to SELECT platform_settings
-- This is needed for branding to work on public pages
CREATE POLICY "Public can view platform settings"
ON platform_settings FOR SELECT
TO public
USING (true);

-- Policy 2: Allow authenticated users to UPDATE platform_settings
-- (Simplified - all authenticated users can update for now)
CREATE POLICY "Authenticated can update platform settings"
ON platform_settings FOR UPDATE
TO authenticated
USING (true)
WITH CHECK (true);

-- Policy 3: Allow authenticated users to INSERT platform_settings
CREATE POLICY "Authenticated can insert platform settings"
ON platform_settings FOR INSERT
TO authenticated
WITH CHECK (true);

-- Policy 4: Allow authenticated users to DELETE platform_settings
CREATE POLICY "Authenticated can delete platform settings"
ON platform_settings FOR DELETE
TO authenticated
USING (true);

-- =====================================================
-- VERIFICATION
-- =====================================================

-- Test as public (should return data)
SELECT * FROM platform_settings;

-- Check current policies
SELECT
  tablename,
  policyname,
  permissive,
  roles,
  cmd
FROM pg_policies
WHERE tablename = 'platform_settings';

-- =====================================================
-- TROUBLESHOOTING
-- =====================================================

-- Check if RLS is enabled
SELECT tablename, rowsecurity
FROM pg_tables
WHERE tablename = 'platform_settings';

-- Check if table has data
SELECT COUNT(*) as row_count FROM platform_settings;

-- Check current user
SELECT auth.uid();
