-- Modules belong to a Course; program_id is denormalized and enforced with the course by a composite FK.
ALTER TABLE courses
    ADD CONSTRAINT courses_program_id_id_key UNIQUE (program_id, id);

CREATE TABLE modules (
    id BIGSERIAL PRIMARY KEY,
    program_id BIGINT NOT NULL,
    course_id BIGINT NOT NULL,
    name VARCHAR(255) NOT NULL,
    description TEXT,
    icon TEXT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMPTZ,
    CONSTRAINT modules_course_scope_fkey
        FOREIGN KEY (program_id, course_id)
        REFERENCES courses (program_id, id)
        ON DELETE CASCADE
);

CREATE INDEX idx_modules_course_id ON modules (course_id);
CREATE INDEX idx_modules_program_id ON modules (program_id);
CREATE INDEX idx_modules_program_course_created ON modules (program_id, course_id, created_at DESC);
