-- +goose Up

CREATE TABLE assignment_student_questions (
    id BIGSERIAL PRIMARY KEY,
    assignment_id BIGINT NOT NULL,
    student_id BIGINT NOT NULL,
    question_id BIGINT NOT NULL REFERENCES questions(id) ON DELETE CASCADE,
    position INTEGER NOT NULL CHECK (position > 0),
    source_bucket TEXT NOT NULL CHECK (btrim(source_bucket) <> ''),
    source_topic question_topic,
    source_difficulty question_difficulty,
    generator_seed BIGINT,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CONSTRAINT assignment_student_questions_assignment_student_fkey
        FOREIGN KEY (assignment_id, student_id)
        REFERENCES assignment_assignees(assignment_id, student_id)
        ON DELETE CASCADE,
    CONSTRAINT assignment_student_questions_assignment_student_question_key
        UNIQUE (assignment_id, student_id, question_id),
    CONSTRAINT assignment_student_questions_assignment_student_position_key
        UNIQUE (assignment_id, student_id, position)
);

CREATE INDEX idx_assignment_student_questions_assignment_student
    ON assignment_student_questions (assignment_id, student_id);

-- +goose Down

DROP INDEX IF EXISTS idx_assignment_student_questions_assignment_student;
DROP TABLE IF EXISTS assignment_student_questions;
