ALTER TABLE brand_questions
    ADD COLUMN IF NOT EXISTS current_version_id BIGINT;

CREATE TABLE IF NOT EXISTS brand_question_versions (
    id            BIGSERIAL PRIMARY KEY,
    question_id   BIGINT NOT NULL REFERENCES brand_questions(id),
    question_text TEXT NOT NULL,
    question_hash VARCHAR(64) NOT NULL,
    version_no    INT NOT NULL,
    is_active     BOOLEAN NOT NULL DEFAULT true,
    created_at    TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT uk_question_version_no UNIQUE (question_id, version_no)
);

CREATE INDEX IF NOT EXISTS idx_question_hash ON brand_question_versions(question_hash);

INSERT INTO brand_question_versions (question_id, question_text, question_hash, version_no, is_active)
SELECT q.id,
       q.question_text,
       md5(q.question_text),
       1,
       true
FROM brand_questions q
WHERE NOT EXISTS (
    SELECT 1
    FROM brand_question_versions v
    WHERE v.question_id = q.id
);

UPDATE brand_questions q
SET current_version_id = v.id
FROM brand_question_versions v
WHERE v.question_id = q.id
  AND v.version_no = 1;

ALTER TABLE brand_questions
    DROP COLUMN IF EXISTS question_text;
