{"-- Enable Row Level Security on all tables that currently don't have it
ALTER TABLE public.ai_models ENABLE ROW LEVEL SECURITY","ALTER TABLE public.detection_rules ENABLE ROW LEVEL SECURITY","ALTER TABLE public.security_zones ENABLE ROW LEVEL SECURITY","-- Create RLS policies for ai_models (organization-based access)
CREATE POLICY \"Users can view AI models in their organization\" 
ON public.ai_models 
FOR SELECT 
USING (
  EXISTS (
    SELECT 1 FROM user_roles ur 
    WHERE ur.user_id = auth.uid() 
    AND ur.organization_id IS NOT NULL
  )
)","CREATE POLICY \"Admins can manage AI models\" 
ON public.ai_models 
FOR ALL 
USING (
  EXISTS (
    SELECT 1 FROM user_roles ur 
    WHERE ur.user_id = auth.uid() 
    AND ur.role = 'admin'
  )
)","-- Create RLS policies for detection_rules (organization-based access)
CREATE POLICY \"Users can view detection rules in their organization\" 
ON public.detection_rules 
FOR SELECT 
USING (
  EXISTS (
    SELECT 1 FROM user_roles ur 
    WHERE ur.user_id = auth.uid() 
    AND ur.organization_id = detection_rules.organization_id
  )
)","CREATE POLICY \"Admins and managers can manage detection rules\" 
ON public.detection_rules 
FOR ALL 
USING (
  EXISTS (
    SELECT 1 FROM user_roles ur 
    WHERE ur.user_id = auth.uid() 
    AND ur.organization_id = detection_rules.organization_id
    AND ur.role IN ('admin', 'manager')
  )
)","-- Create RLS policies for security_zones (branch-based access)
CREATE POLICY \"Users can view security zones in their organization\" 
ON public.security_zones 
FOR SELECT 
USING (
  EXISTS (
    SELECT 1 FROM user_roles ur 
    JOIN branches b ON ur.organization_id = b.organization_id
    WHERE ur.user_id = auth.uid() 
    AND b.id = security_zones.branch_id
  )
)","CREATE POLICY \"Admins and managers can manage security zones\" 
ON public.security_zones 
FOR ALL 
USING (
  EXISTS (
    SELECT 1 FROM user_roles ur 
    JOIN branches b ON ur.organization_id = b.organization_id
    WHERE ur.user_id = auth.uid() 
    AND b.id = security_zones.branch_id
    AND ur.role IN ('admin', 'manager')
  )
)","-- Fix function security by setting proper search_path
CREATE OR REPLACE FUNCTION public.update_modified_column()
RETURNS trigger
LANGUAGE plpgsql
SECURITY DEFINER
AS $function$
BEGIN
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$function$","CREATE OR REPLACE FUNCTION public.get_user_role(user_id uuid)
RETURNS user_role
LANGUAGE sql
SECURITY DEFINER
AS $function$
  SELECT role FROM public.user_roles WHERE user_id = $1 LIMIT 1
$function$"}