-- v1.1.5: extend the triggers framework to recognise `pubsub` as the
-- sixth concrete kind. Same Layout-E shape as files (0019): two CHECK
-- constraints widen, one new detail table.
--
-- Pub/sub fans out at PUBLISH time (one outbox row per matching trigger,
-- written by the PubsubServiceImpl), so the dispatcher needs no pubsub-
-- specific branching — a pubsub outbox row dispatches like any other
-- async trigger.

-- Extend triggers.kind to include 'pubsub'.
ALTER TABLE triggers DROP CONSTRAINT triggers_kind_check;
ALTER TABLE triggers ADD CONSTRAINT triggers_kind_check
    CHECK (kind IN ('kv', 'dead_letter', 'docs', 'cron', 'files', 'pubsub'));

-- Extend outbox.source_kind to include 'pubsub'.
ALTER TABLE outbox DROP CONSTRAINT outbox_source_kind_check;
ALTER TABLE outbox ADD CONSTRAINT outbox_source_kind_check
    CHECK (source_kind IN ('http', 'kv', 'dead_letter', 'docs',
                           'cron', 'files', 'pubsub'));

-- One row per pubsub trigger. `topic_pattern` is "exact", "prefix.*",
-- or "*" — validated in Rust at trigger creation. Topics are implicit
-- on first publish; the external-subscribable `topics` table is v1.1.6.
CREATE TABLE pubsub_trigger_details (
    trigger_id     UUID PRIMARY KEY REFERENCES triggers(id) ON DELETE CASCADE,
    topic_pattern  TEXT NOT NULL
);

-- Hot lookup for fan-out: "all enabled pubsub triggers in app X".
-- Third partial index of its kind (after v1.1.1's idx_triggers_app_kind_
-- enabled); partial indexes are tiny and the planner picks the narrowest.
CREATE INDEX idx_triggers_app_pubsub_enabled
    ON triggers (app_id, kind)
    WHERE enabled = TRUE AND kind = 'pubsub';
