-- Tier 2 Block A — editable RSVPs.
--
-- Guests can revisit their invitation link after submitting and change their
-- response or plus-one count. Every prior state is captured in rsvp_revisions
-- so the host can see the trail of edits.
--
-- The plan called this 0004_rsvp_edits in TIER2_PLAN.md; using the next free
-- slot (0007) because 0004–0006 were taken by Tier 1 work.

CREATE TABLE IF NOT EXISTS rsvp_revisions (
    id              UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    rsvp_id         UUID NOT NULL REFERENCES rsvps(id) ON DELETE CASCADE,
    prev_response   rsvp_response NOT NULL,
    prev_plus_ones  INTEGER NOT NULL,
    prev_dietary    TEXT,
    changed_at      TIMESTAMPTZ NOT NULL DEFAULT now()
);

CREATE INDEX IF NOT EXISTS idx_rsvp_revisions_rsvp
    ON rsvp_revisions(rsvp_id, changed_at DESC);

-- Hard cap on how many times a guest can edit. The numeric cap (5) is
-- enforced in Go; storing the running count avoids a count(*) on every PATCH.
ALTER TABLE rsvps
    ADD COLUMN IF NOT EXISTS edit_count SMALLINT NOT NULL DEFAULT 0;
