-- §11.6 (cont., v1.2 Hierarchies): group-shared DOCS collections.
--
-- Extends the shared-collection machinery (0052 registry + 0053 group_kv_entries)
-- from KV to the queryable-JSON `docs` store. The registry's `kind`
-- discriminator was built for exactly this — widen its CHECK to admit 'docs',
-- and add a group-keyed storage table mirroring `docs` (0013).

-- Widen the marker kind allow-list. The constraint was an inline column CHECK,
-- so Postgres auto-named it `group_collections_kind_check`.
ALTER TABLE group_collections
    DROP CONSTRAINT group_collections_kind_check,
    ADD CONSTRAINT group_collections_kind_check CHECK (kind IN ('kv', 'docs'));

-- Group-keyed docs store. Identity tuple `(group_id, collection, id)` — keyed
-- by the OWNING GROUP, not an app (the shared rows belong to the group). `id`
-- is a server-generated UUID, as in `docs`. CASCADE on group delete (data dies
-- with its group; an app delete leaves it), matching group_kv_entries (0053).
CREATE TABLE group_docs (
    group_id    UUID NOT NULL REFERENCES groups(id) ON DELETE CASCADE,
    collection  TEXT NOT NULL,
    id          UUID NOT NULL,
    data        JSONB NOT NULL,
    created_at  TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at  TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    PRIMARY KEY (group_id, collection, id)
);

-- "all docs in group X / collection Y" — mirrors idx_docs_app_collection (0013).
CREATE INDEX idx_group_docs_group_collection ON group_docs (group_id, collection);

-- GIN on JSONB (jsonb_path_ops) for the find DSL's equality/containment, same
-- as idx_docs_data_gin (0013).
CREATE INDEX idx_group_docs_data_gin ON group_docs USING GIN (data jsonb_path_ops);
