-- Migration 022: Interactive Training Video Pipeline
-- Adds checkpoints, checkpoint progress tracking, and links quiz questions to checkpoints

-- Checkpoints pro Modul-Video (pausiert Video bei bestimmtem Timestamp)
CREATE TABLE IF NOT EXISTS training_checkpoints (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    module_id UUID NOT NULL REFERENCES training_modules(id) ON DELETE CASCADE,
    checkpoint_index INTEGER NOT NULL,
    title TEXT NOT NULL,
    timestamp_seconds DOUBLE PRECISION NOT NULL,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    UNIQUE(module_id, checkpoint_index)
);

-- Checkpoint-Fortschritt pro User-Assignment
CREATE TABLE IF NOT EXISTS training_checkpoint_progress (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    assignment_id UUID NOT NULL REFERENCES training_assignments(id) ON DELETE CASCADE,
    checkpoint_id UUID NOT NULL REFERENCES training_checkpoints(id) ON DELETE CASCADE,
    passed BOOLEAN DEFAULT FALSE,
    attempts INTEGER DEFAULT 0,
    last_attempt_at TIMESTAMPTZ,
    created_at TIMESTAMPTZ DEFAULT NOW(),
    UNIQUE(assignment_id, checkpoint_id)
);

-- Quiz-Fragen koennen jetzt optional einem Checkpoint zugeordnet sein
ALTER TABLE training_quiz_questions ADD COLUMN IF NOT EXISTS checkpoint_id UUID REFERENCES training_checkpoints(id);

-- Checkpoint-Index auf Media (fuer Manifest-Zuordnung)
ALTER TABLE training_media ADD COLUMN IF NOT EXISTS checkpoint_index INTEGER;

-- Indices for performance
CREATE INDEX IF NOT EXISTS idx_training_checkpoints_module ON training_checkpoints(module_id);
CREATE INDEX IF NOT EXISTS idx_training_checkpoint_progress_assignment ON training_checkpoint_progress(assignment_id);
CREATE INDEX IF NOT EXISTS idx_training_checkpoint_progress_checkpoint ON training_checkpoint_progress(checkpoint_id);
CREATE INDEX IF NOT EXISTS idx_training_quiz_questions_checkpoint ON training_quiz_questions(checkpoint_id);
