ALTER TABLE brand_keywords
    ADD COLUMN IF NOT EXISTS layer VARCHAR(8) NOT NULL DEFAULT 'L2',
    ADD COLUMN IF NOT EXISTS seed_word VARCHAR(200),
    ADD COLUMN IF NOT EXISTS source VARCHAR(32) NOT NULL DEFAULT 'manual';

ALTER TABLE brand_keywords
    DROP CONSTRAINT IF EXISTS ck_brand_keywords_layer,
    DROP CONSTRAINT IF EXISTS ck_brand_keywords_source;

ALTER TABLE brand_keywords
    ADD CONSTRAINT ck_brand_keywords_layer
        CHECK (layer IN ('L1','L2','L3','L4','L5')),
    ADD CONSTRAINT ck_brand_keywords_source
        CHECK (source IN ('manual','combination','ai_distill','auto'));

CREATE INDEX IF NOT EXISTS idx_brand_keywords_internal_source
    ON brand_keywords (tenant_id, brand_id, source)
    WHERE deleted_at IS NULL;

ALTER TABLE brand_questions
    ADD COLUMN IF NOT EXISTS layer VARCHAR(8) NOT NULL DEFAULT 'L2',
    ADD COLUMN IF NOT EXISTS intent VARCHAR(16) NOT NULL DEFAULT 'informational',
    ADD COLUMN IF NOT EXISTS source VARCHAR(32) NOT NULL DEFAULT 'manual';

ALTER TABLE brand_questions
    DROP CONSTRAINT IF EXISTS ck_brand_questions_layer,
    DROP CONSTRAINT IF EXISTS ck_brand_questions_intent,
    DROP CONSTRAINT IF EXISTS ck_brand_questions_source;

ALTER TABLE brand_questions
    ADD CONSTRAINT ck_brand_questions_layer
        CHECK (layer IN ('L1','L2','L3','L4','L5')),
    ADD CONSTRAINT ck_brand_questions_intent
        CHECK (intent IN ('informational','evaluative','decisional')),
    ADD CONSTRAINT ck_brand_questions_source
        CHECK (source IN ('manual','combination','ai_distill'));

CREATE INDEX IF NOT EXISTS idx_brand_questions_intent
    ON brand_questions (tenant_id, brand_id, intent)
    WHERE deleted_at IS NULL;

CREATE UNIQUE INDEX IF NOT EXISTS uk_brand_question_text_active
    ON brand_questions (tenant_id, brand_id, lower(btrim(question_text)))
    WHERE deleted_at IS NULL;
