-- Migration 008: post-commit event fan-out for the SSE stream (SG8/SG10).
-- Events are INSERTed in the same transaction as the state change; pg_notify
-- fires at COMMIT, so subscribers only ever see committed events. Payload is
-- kept minimal (NOTIFY has an 8000-byte limit); consumers needing the full
-- event fetch it by id.

CREATE OR REPLACE FUNCTION notify_oikos_event() RETURNS trigger AS $$
BEGIN
    PERFORM pg_notify('oikos_events', json_build_object(
        'id', NEW.id,
        'ts', NEW.ts,
        'type', NEW.type,
        'entity_id', NEW.entity_id,
        'severity', NEW.severity,
        'source', NEW.source,
        'correlation_id', NEW.correlation_id
    )::text);
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

DROP TRIGGER IF EXISTS trg_events_notify ON events;
CREATE TRIGGER trg_events_notify AFTER INSERT ON events
    FOR EACH ROW EXECUTE FUNCTION notify_oikos_event();
