{"-- 1) Ensure 'representative' value exists in user_role enum
DO $$
BEGIN
  IF NOT EXISTS (
    SELECT 1
    FROM pg_type t
    JOIN pg_enum e ON t.oid = e.enumtypid
    WHERE t.typname = 'user_role' AND e.enumlabel = 'representative'
  ) THEN
    ALTER TYPE public.user_role ADD VALUE 'representative';
  END IF;
END $$","-- 2) Create screen_permissions table for page-level access control
CREATE TABLE IF NOT EXISTS public.screen_permissions (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  screen_key text NOT NULL UNIQUE,       -- stable key e.g. \"dashboard\", \"alerts\", \"organization-users\"
  path text NOT NULL,                    -- route path e.g. \"/dashboard\"
  title_en text,
  title_ar text,
  description_en text,
  description_ar text,
  allowed_roles text[] NOT NULL DEFAULT '{}'::text[],
  allow_super_admin boolean NOT NULL DEFAULT true,
  is_active boolean NOT NULL DEFAULT true,
  created_by uuid,
  created_at timestamptz NOT NULL DEFAULT now(),
  updated_at timestamptz NOT NULL DEFAULT now()
)","-- 3) Enable Row Level Security
ALTER TABLE public.screen_permissions ENABLE ROW LEVEL SECURITY","-- 4) Policies
DROP POLICY IF EXISTS \"Super admin can manage screen permissions\" ON public.screen_permissions","CREATE POLICY \"Super admin can manage screen permissions\"
ON public.screen_permissions
FOR ALL
USING (is_current_user_super_admin())
WITH CHECK (is_current_user_super_admin())","DROP POLICY IF EXISTS \"Authenticated users can view active screen permissions\" ON public.screen_permissions","CREATE POLICY \"Authenticated users can view active screen permissions\"
ON public.screen_permissions
FOR SELECT
USING (is_active = true)","-- 5) Trigger to auto-update updated_at
DROP TRIGGER IF EXISTS handle_screen_permissions_updated_at ON public.screen_permissions","CREATE TRIGGER handle_screen_permissions_updated_at
BEFORE UPDATE ON public.screen_permissions
FOR EACH ROW
EXECUTE FUNCTION public.update_modified_column()"}