-- Fix search_path security warnings - drop triggers first, then recreate functions

-- Drop triggers
DROP TRIGGER IF EXISTS trigger_set_incident_number ON incidents;
DROP TRIGGER IF EXISTS trigger_update_incident_alert_count ON incident_alerts;

-- Drop functions
DROP FUNCTION IF EXISTS generate_incident_number();
DROP FUNCTION IF EXISTS set_incident_number();
DROP FUNCTION IF EXISTS update_incident_alert_count();

-- Recreate functions with proper search_path
CREATE OR REPLACE FUNCTION generate_incident_number()
RETURNS TEXT 
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
BEGIN
  RETURN 'INC-' || LPAD(nextval('incident_number_seq')::TEXT, 6, '0');
END;
$$;

CREATE OR REPLACE FUNCTION set_incident_number()
RETURNS TRIGGER 
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
BEGIN
  IF NEW.incident_number IS NULL THEN
    NEW.incident_number := generate_incident_number();
  END IF;
  RETURN NEW;
END;
$$;

CREATE OR REPLACE FUNCTION update_incident_alert_count()
RETURNS TRIGGER 
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
BEGIN
  IF TG_OP = 'INSERT' THEN
    UPDATE incidents 
    SET alert_count = alert_count + 1,
        updated_at = NOW()
    WHERE id = NEW.incident_id;
  ELSIF TG_OP = 'DELETE' THEN
    UPDATE incidents 
    SET alert_count = alert_count - 1,
        updated_at = NOW()
    WHERE id = OLD.incident_id;
  END IF;
  RETURN NEW;
END;
$$;

-- Recreate triggers
CREATE TRIGGER trigger_set_incident_number
  BEFORE INSERT ON incidents
  FOR EACH ROW
  EXECUTE FUNCTION set_incident_number();

CREATE TRIGGER trigger_update_incident_alert_count
  AFTER INSERT OR DELETE ON incident_alerts
  FOR EACH ROW
  EXECUTE FUNCTION update_incident_alert_count();