-- Catalog of LMS personas (coach/avatar profiles) referenced by Learn English + exam-prep practices.
CREATE TABLE lms_personas (
    id BIGSERIAL PRIMARY KEY,
    name VARCHAR(255) NOT NULL,
    description TEXT,
    avatar_url TEXT,
    is_active BOOLEAN NOT NULL DEFAULT TRUE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMPTZ
);

CREATE INDEX idx_lms_personas_is_active ON lms_personas (is_active)
WHERE is_active;

CREATE INDEX idx_lms_personas_created_at ON lms_personas (created_at DESC);

-- persona_id historically referenced users.id; personas are now catalog rows on lms_personas.
ALTER TABLE lms_practices DROP CONSTRAINT IF EXISTS lms_practices_persona_id_fkey;

UPDATE lms_practices
SET persona_id = NULL
WHERE persona_id IS NOT NULL;

ALTER TABLE lms_practices
    ADD CONSTRAINT lms_practices_persona_id_fkey FOREIGN KEY (persona_id) REFERENCES lms_personas (id) ON DELETE SET NULL;

ALTER TABLE exam_prep.lesson_practices DROP CONSTRAINT IF EXISTS lesson_practices_persona_id_fkey;

UPDATE exam_prep.lesson_practices
SET persona_id = NULL
WHERE persona_id IS NOT NULL;

ALTER TABLE exam_prep.lesson_practices
    ADD CONSTRAINT lesson_practices_persona_id_fkey FOREIGN KEY (persona_id) REFERENCES lms_personas (id) ON DELETE SET NULL;
