-- Add version management columns to ai_message for edit/regenerate with version tracking
-- version_group_id: groups all versions of the same message (original + edits)
-- version_number: sequential version within the group (1 = original, 2 = first edit, etc.)
-- is_latest: marks the current active version in the group

ALTER TABLE ai_message
    ADD COLUMN IF NOT EXISTS version_group_id UUID,
    ADD COLUMN IF NOT EXISTS version_number INT NOT NULL DEFAULT 1,
    ADD COLUMN IF NOT EXISTS is_latest BOOLEAN NOT NULL DEFAULT true;

CREATE INDEX IF NOT EXISTS idx_ai_msg_version_group ON ai_message (version_group_id, version_number);
CREATE INDEX IF NOT EXISTS idx_ai_msg_version_latest ON ai_message (version_group_id, is_latest) WHERE is_latest = true;

-- Backfill: set version_group_id = id for existing messages (each existing message is its own group v1)
UPDATE ai_message SET version_group_id = id WHERE version_group_id IS NULL;