-- Create function and trigger to notify SSE on planilla changes
CREATE OR REPLACE FUNCTION notify_planilla_change() RETURNS trigger AS $$
DECLARE
  payload TEXT;
BEGIN
  payload := json_build_object(
    'table', TG_TABLE_NAME,
    'operation', TG_OP,
    'old', row_to_json(OLD),
    'new', row_to_json(NEW)
  )::text;
  PERFORM pg_notify('sse_events', payload);
  IF TG_OP = 'DELETE' THEN
    RETURN OLD;
  ELSE
    RETURN NEW;
  END IF;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS planilla_notify_trigger ON "Planilla";
CREATE TRIGGER planilla_notify_trigger
  AFTER INSERT OR UPDATE OR DELETE ON "Planilla"
  DEFERRABLE INITIALLY DEFERRED
  FOR EACH ROW
  EXECUTE PROCEDURE notify_planilla_change();
