-- Phase 6: Auth Function Optimization & Duplicate Policy Cleanup
-- Part A: Fix auth_rls_initplan warnings (2 policies)

-- 1. Optimize email_aliases.email_aliases_select_admin
DROP POLICY IF EXISTS "email_aliases_select_admin" ON public.email_aliases;
CREATE POLICY "email_aliases_select_admin" ON public.email_aliases
  FOR SELECT
  USING (
    (COALESCE((((SELECT auth.jwt()) ->> 'is_admin'::text))::boolean, false) = true) 
    AND has_aal2()
  );

-- 2. Optimize contact_submissions "Users can view own contact submissions"
DROP POLICY IF EXISTS "Users can view own contact submissions" ON public.contact_submissions;
CREATE POLICY "Users can view own contact submissions" ON public.contact_submissions
  FOR SELECT
  USING (
    ((SELECT auth.uid()) = user_id) 
    OR (((SELECT auth.uid()) IS NOT NULL) AND (email = ((SELECT auth.jwt()) ->> 'email'::text)))
  );

-- Part B: Remove duplicate policies (8 policies)

-- Group 1: Remove short-named duplicate policies on tech specs tables
DROP POLICY IF EXISTS "Public read model tech specs" ON public.ride_model_technical_specifications;
DROP POLICY IF EXISTS "Moderators manage model tech specs" ON public.ride_model_technical_specifications;

DROP POLICY IF EXISTS "Public read name history" ON public.ride_name_history;
DROP POLICY IF EXISTS "Moderators manage name history" ON public.ride_name_history;

DROP POLICY IF EXISTS "Public read ride tech specs" ON public.ride_technical_specifications;
DROP POLICY IF EXISTS "Moderators manage ride tech specs" ON public.ride_technical_specifications;

-- Group 2: Remove overlapping moderator view policy on profiles
DROP POLICY IF EXISTS "Admins and moderators can view all profiles" ON public.profiles;

-- Group 3: Consolidate list_items policies (ALL command already includes SELECT)
DROP POLICY IF EXISTS "Users view own list items" ON public.list_items;