{"-- Finalized safe migration

-- 1) Ensure 'representative' exists in user_role enum (idempotent)
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 table if missing, with minimal required columns
CREATE TABLE IF NOT EXISTS public.screen_permissions (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  screen_key text NOT NULL UNIQUE,
  path text NOT NULL,
  created_at timestamptz NOT NULL DEFAULT now(),
  updated_at timestamptz NOT NULL DEFAULT now()
)","-- 3) Ensure all needed columns exist (idempotent)
ALTER TABLE public.screen_permissions ADD COLUMN IF NOT EXISTS title_en text","ALTER TABLE public.screen_permissions ADD COLUMN IF NOT EXISTS title_ar text","ALTER TABLE public.screen_permissions ADD COLUMN IF NOT EXISTS description_en text","ALTER TABLE public.screen_permissions ADD COLUMN IF NOT EXISTS description_ar text","ALTER TABLE public.screen_permissions ADD COLUMN IF NOT EXISTS allowed_roles text[]","ALTER TABLE public.screen_permissions ALTER COLUMN allowed_roles SET DEFAULT '{}'::text[]","ALTER TABLE public.screen_permissions ALTER COLUMN allowed_roles SET NOT NULL","ALTER TABLE public.screen_permissions ADD COLUMN IF NOT EXISTS allow_super_admin boolean","ALTER TABLE public.screen_permissions ALTER COLUMN allow_super_admin SET DEFAULT true","ALTER TABLE public.screen_permissions ALTER COLUMN allow_super_admin SET NOT NULL","ALTER TABLE public.screen_permissions ADD COLUMN IF NOT EXISTS is_active boolean","ALTER TABLE public.screen_permissions ALTER COLUMN is_active SET DEFAULT true","ALTER TABLE public.screen_permissions ALTER COLUMN is_active SET NOT NULL","ALTER TABLE public.screen_permissions ADD COLUMN IF NOT EXISTS created_by uuid","-- 4) Enable RLS
ALTER TABLE public.screen_permissions ENABLE ROW LEVEL SECURITY","-- 5) Policies (drop if exist, then create)
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 (COALESCE(public.screen_permissions.is_active, true) = true)","-- 6) Update trigger for 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()"}