"""Helpers for managing the quiz ↔ question junction table."""
from sqlalchemy.orm import Session

from app.models.question import Question
from app.models.quiz_question_link import QuizQuestionLink


def get_quiz_questions(db: Session, quiz_id: int) -> list[Question]:
    """Fetch questions for a quiz in position order via junction table."""
    links = (
        db.query(QuizQuestionLink)
        .filter(QuizQuestionLink.quiz_id == quiz_id)
        .order_by(QuizQuestionLink.position)
        .all()
    )
    if not links:
        return []
    q_map = {
        q.id: q
        for q in db.query(Question).filter(Question.id.in_([l.question_id for l in links])).all()
    }
    return [q_map[l.question_id] for l in links if l.question_id in q_map]


def add_questions_to_quiz(db: Session, quiz_id: int, question_ids: list[int], start_pos: int = 0):
    """Add question links to a quiz (skips duplicates)."""
    existing = {
        l.question_id
        for l in db.query(QuizQuestionLink).filter(QuizQuestionLink.quiz_id == quiz_id).all()
    }
    for i, qid in enumerate(question_ids):
        if qid not in existing:
            db.add(QuizQuestionLink(quiz_id=quiz_id, question_id=qid, position=start_pos + i))


def question_in_quiz(db: Session, quiz_id: int, question_id: int) -> bool:
    return db.query(QuizQuestionLink).filter(
        QuizQuestionLink.quiz_id == quiz_id,
        QuizQuestionLink.question_id == question_id,
    ).first() is not None


def remove_question_from_quiz(db: Session, quiz_id: int, question_id: int):
    db.query(QuizQuestionLink).filter(
        QuizQuestionLink.quiz_id == quiz_id,
        QuizQuestionLink.question_id == question_id,
    ).delete()
