-- §11.6 D3 (dead-letter store for group SHARED durable queues).
--
-- Previously an exhausted shared-queue message was `drop_exhausted()`-ed with a
-- warning — silent data loss. Per-app queues persist to `dead_letters` (0010);
-- this is the symmetric group store, keyed by `group_id` (the shared-queue owner)
-- + `collection` (a group has many shared queues) instead of `app_id`.
--
-- CASCADE on the group mirrors `group_queue_messages` (0065): deleting the group
-- drops its dead-letters; an app delete leaves them (the data belongs to the
-- group, not the consuming app). No `app_id` — a shared-queue message is not
-- owned by whichever descendant happened to consume it.
--
-- Fan-out to a *shared* dead-letter TRIGGER is deferred (would need a new shared
-- dead-letter trigger kind); M2 stops the data loss + makes exhausted messages
-- operator-visible (GET /api/v1/admin/groups/{id}/dead-letters).

CREATE TABLE group_dead_letters (
    id                 UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    group_id           UUID NOT NULL REFERENCES groups(id) ON DELETE CASCADE,
    -- The shared-queue collection name the exhausted message came from.
    collection         TEXT NOT NULL,
    -- The group_queue_messages.id row that exhausted retries (already deleted).
    original_event_id  UUID NOT NULL,
    source             TEXT NOT NULL,
    op                 TEXT NOT NULL,
    -- The materialized consumer copy's trigger/script (nullable, mirrors 0010).
    trigger_id         UUID,
    script_id          UUID,
    payload            JSONB NOT NULL,
    attempt_count      INT  NOT NULL,
    first_attempt_at   TIMESTAMPTZ NOT NULL,
    last_attempt_at    TIMESTAMPTZ NOT NULL,
    last_error         TEXT NOT NULL,
    created_at         TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    resolved_at        TIMESTAMPTZ,
    resolution         TEXT
        CHECK (resolution IN
            ('replayed', 'ignored', 'handled_by_script', 'handler_failed'))
);

-- Operator listing: newest-first per group (GET .../groups/{id}/dead-letters).
CREATE INDEX idx_group_dead_letters_group
    ON group_dead_letters (group_id, created_at DESC);
