{"-- Create alert_template_industries table to link alert templates with industries
CREATE TABLE public.alert_template_industries (
  id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  alert_template_id UUID NOT NULL REFERENCES public.alert_templates(id) ON DELETE CASCADE,
  industry_id UUID NOT NULL REFERENCES public.industries(id) ON DELETE CASCADE,
  created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
  UNIQUE(alert_template_id, industry_id)
)","-- Enable RLS
ALTER TABLE public.alert_template_industries ENABLE ROW LEVEL SECURITY","-- Create policies
CREATE POLICY \"Super admin can manage alert template industries\" 
ON public.alert_template_industries 
FOR ALL 
USING (is_current_user_super_admin())","CREATE POLICY \"Users can view alert template industries in their organization\" 
ON public.alert_template_industries 
FOR SELECT 
USING (EXISTS (
  SELECT 1 FROM user_roles ur
  JOIN organizations o ON o.id = ur.organization_id
  WHERE ur.user_id = auth.uid() 
  AND o.industry_id = alert_template_industries.industry_id
))","-- Update RLS policy for alert_templates to show only templates linked to user's industry or all for super admin
DROP POLICY IF EXISTS \"Users can view alert templates\" ON public.alert_templates","CREATE POLICY \"Users can view alert templates for their industry\" 
ON public.alert_templates 
FOR SELECT 
USING (
  is_current_user_super_admin() OR 
  EXISTS (
    SELECT 1 FROM alert_template_industries ati
    JOIN user_roles ur ON ur.user_id = auth.uid()
    JOIN organizations o ON o.id = ur.organization_id
    WHERE ati.alert_template_id = alert_templates.id
    AND ati.industry_id = o.industry_id
  )
)"}