-- Platform admins can read/write all data across the platform
-- This bypasses org-membership-based RLS for users with is_platform_admin = true

-- Helper function to check if current user is a platform admin
CREATE OR REPLACE FUNCTION is_platform_admin()
RETURNS BOOLEAN AS $$
  SELECT EXISTS (
    SELECT 1 FROM profiles
    WHERE id = auth.uid()
    AND is_platform_admin = true
  );
$$ LANGUAGE sql SECURITY DEFINER STABLE;

-- Organizations: platform admins can do everything
CREATE POLICY "Platform admins full access to organizations" ON organizations
  USING (is_platform_admin()) WITH CHECK (is_platform_admin());

-- Org Members: platform admins can see all memberships
CREATE POLICY "Platform admins full access to org_members" ON org_members
  USING (is_platform_admin()) WITH CHECK (is_platform_admin());

-- Profiles: platform admins can update any profile
CREATE POLICY "Platform admins can update profiles" ON profiles FOR UPDATE
  USING (is_platform_admin()) WITH CHECK (is_platform_admin());

-- Events: platform admins can do everything
CREATE POLICY "Platform admins full access to events" ON events
  USING (is_platform_admin()) WITH CHECK (is_platform_admin());

-- Event members: platform admins can do everything
CREATE POLICY "Platform admins full access to event_members" ON event_members
  USING (is_platform_admin()) WITH CHECK (is_platform_admin());

-- Documents: platform admins can do everything
CREATE POLICY "Platform admins full access to documents" ON documents
  USING (is_platform_admin()) WITH CHECK (is_platform_admin());

-- Kanban boards: platform admins can do everything
CREATE POLICY "Platform admins full access to kanban_boards" ON kanban_boards
  USING (is_platform_admin()) WITH CHECK (is_platform_admin());

-- Calendar events: platform admins can do everything
CREATE POLICY "Platform admins full access to calendar_events" ON calendar_events
  USING (is_platform_admin()) WITH CHECK (is_platform_admin());

-- Org roles: platform admins can do everything
CREATE POLICY "Platform admins full access to org_roles" ON org_roles
  USING (is_platform_admin()) WITH CHECK (is_platform_admin());

-- Org invites: platform admins can do everything
CREATE POLICY "Platform admins full access to org_invites" ON org_invites
  USING (is_platform_admin()) WITH CHECK (is_platform_admin());

-- Event departments: platform admins can do everything
CREATE POLICY "Platform admins full access to event_departments" ON event_departments
  USING (is_platform_admin()) WITH CHECK (is_platform_admin());
