{"-- Create frigate_instances table for managing multiple Frigate devices per branch
CREATE TABLE public.frigate_instances (
  id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  branch_id UUID NOT NULL,
  name TEXT NOT NULL,
  description TEXT,
  host_url TEXT NOT NULL,
  api_key TEXT,
  config_yaml TEXT,
  enabled BOOLEAN NOT NULL DEFAULT true,
  last_sync_at TIMESTAMP WITH TIME ZONE,
  created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
  updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
  UNIQUE(branch_id, name)
)","-- Enable RLS on frigate_instances
ALTER TABLE public.frigate_instances ENABLE ROW LEVEL SECURITY","-- Add frigate_instance_id to cameras table
ALTER TABLE public.cameras ADD COLUMN frigate_instance_id UUID REFERENCES public.frigate_instances(id)","-- Create RLS policies for frigate_instances
CREATE POLICY \"Super admin can manage all frigate instances\" 
ON public.frigate_instances 
FOR ALL 
USING (is_current_user_super_admin())","CREATE POLICY \"Org admins can manage frigate instances in their organization\" 
ON public.frigate_instances 
FOR ALL 
USING (
  EXISTS (
    SELECT 1 FROM branches b
    JOIN user_roles ur ON ur.organization_id = b.organization_id
    WHERE b.id = frigate_instances.branch_id 
    AND ur.user_id = auth.uid() 
    AND ur.role IN ('admin', 'manager')
  )
)","CREATE POLICY \"Users can view frigate instances in their organization\" 
ON public.frigate_instances 
FOR SELECT 
USING (
  EXISTS (
    SELECT 1 FROM branches b
    JOIN user_roles ur ON ur.organization_id = b.organization_id
    WHERE b.id = frigate_instances.branch_id 
    AND ur.user_id = auth.uid()
  )
)","-- Create trigger for updated_at
CREATE TRIGGER update_frigate_instances_updated_at
  BEFORE UPDATE ON public.frigate_instances
  FOR EACH ROW
  EXECUTE FUNCTION public.update_modified_column()","-- Update existing cameras to link with frigate instances (optional - can be done manually)
-- This is just a placeholder structure - actual linking would be done through the UI"}