CREATE TABLE IF NOT EXISTS sub_module_practices (
    id BIGSERIAL PRIMARY KEY,
    sub_module_id BIGINT NOT NULL REFERENCES sub_modules(id) ON DELETE CASCADE,
    title VARCHAR(255) NOT NULL,
    description TEXT,
    thumbnail TEXT,
    intro_video_url TEXT,
    question_set_id BIGINT NOT NULL REFERENCES question_sets(id) ON DELETE CASCADE,
    display_order INT NOT NULL DEFAULT 0,
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    UNIQUE(question_set_id)
);

-- If the table already existed from older unified hierarchy migrations,
-- backfill missing columns so practices keep their own richer schema.
ALTER TABLE sub_module_practices
ADD COLUMN IF NOT EXISTS title VARCHAR(255);

ALTER TABLE sub_module_practices
ADD COLUMN IF NOT EXISTS description TEXT;

ALTER TABLE sub_module_practices
ADD COLUMN IF NOT EXISTS thumbnail TEXT;

UPDATE sub_module_practices
SET title = COALESCE(NULLIF(title, ''), 'Practice')
WHERE title IS NULL OR title = '';

ALTER TABLE sub_module_practices
ALTER COLUMN title SET NOT NULL;

CREATE INDEX IF NOT EXISTS idx_sub_module_practices_sub_module_id
ON sub_module_practices(sub_module_id);

