-- mig 116 — t-paliad-225 / m/paliad#61 Slice C — template versioning.
--
-- Design: docs/design-user-checklists-2026-05-20.md §3.4 / §6.
--
-- Adds an integer version counter to paliad.checklists that bumps on
-- every meaningful edit (body or title — see
-- ChecklistTemplateService.Update). Adds a matching template_version
-- column on paliad.checklist_instances so the instance detail page can
-- surface "the template you instantiated from has been updated" and
-- offer a diff view.
--
-- Existing rows backfill to version=1 / template_version=NULL. The
-- NULL on instances means "we don't know which version was snapshotted"
-- (pre-Slice-C row); the snapshot column is still authoritative for
-- rendering, but the "outdated" badge stays off because we can't
-- compare.
--
-- Idempotent throughout.

ALTER TABLE paliad.checklists
    ADD COLUMN IF NOT EXISTS version int NOT NULL DEFAULT 1;

-- Backfill any rows that somehow ended up at 0 (shouldn't happen with
-- DEFAULT 1, but defensive — the column was added with default so this
-- is a no-op on the live DB).
UPDATE paliad.checklists SET version = 1 WHERE version < 1;

COMMENT ON COLUMN paliad.checklists.version IS
    'Monotonic version counter, bumps in ChecklistTemplateService.Update '
    'whenever body or title changes. Used by the instance detail page '
    'to show an "outdated" badge when the user''s snapshot is older.';

ALTER TABLE paliad.checklist_instances
    ADD COLUMN IF NOT EXISTS template_version int;

COMMENT ON COLUMN paliad.checklist_instances.template_version IS
    'Snapshot of paliad.checklists.version at instance create time. '
    'NULL for pre-Slice-C rows where the version wasn''t captured; the '
    '"outdated" badge stays off in that case.';
