-- §11.6 (cont., v1.2 Hierarchies): group-shared FILES collections.
--
-- Extends the shared-collection machinery (0052 registry + the per-kind stores
-- 0053 group_kv_entries / 0054 group_docs) from KV/docs to the filesystem-backed
-- `files` blob store. The registry's `kind` discriminator was built for exactly
-- this — widen its CHECK to admit 'files', and add a group-keyed metadata table
-- mirroring `files` (0018).

-- Widen the marker kind allow-list (auto-named `group_collections_kind_check`,
-- per 0052's inline column CHECK; 0054 widened it to ('kv','docs')).
ALTER TABLE group_collections
    DROP CONSTRAINT group_collections_kind_check,
    ADD CONSTRAINT group_collections_kind_check CHECK (kind IN ('kv', 'docs', 'files'));

-- Group-keyed file metadata. Identity tuple `(group_id, collection, id)` — keyed
-- by the OWNING GROUP, not an app (the shared blobs belong to the group). The
-- bytes live on disk at
--   <PICLOUD_FILES_ROOT>/files/groups/<group_id>/<collection>/<id[0:2]>/<id>
-- (a `groups/` infix disjoint from the per-app `files/<app_id>/...` subtree, so
-- the orphan sweeper covers both with one walk). CASCADE on group delete (the
-- metadata dies with its group; an app delete leaves it), matching 0053/0054.
CREATE TABLE group_files (
    group_id        UUID NOT NULL REFERENCES groups(id) ON DELETE CASCADE,
    collection      TEXT NOT NULL,
    id              UUID NOT NULL,
    name            TEXT NOT NULL,
    content_type    TEXT NOT NULL,
    size_bytes      BIGINT NOT NULL,
    checksum_sha256 TEXT NOT NULL,           -- hex, 64 chars, lowercase
    created_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    updated_at      TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    PRIMARY KEY (group_id, collection, id)
);

-- List + cursor pagination scans by (group_id, collection) — mirrors
-- idx_files_app_collection (0018).
CREATE INDEX idx_group_files_group_collection ON group_files (group_id, collection);
