<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * Creates the self_paced_learning_progress table — records which
     * Course_SubTopics a Trainee has marked as read for a given Enrollment.
     * The unique constraint on (enrollment_id, subtopic_id) enforces monotonicity.
     */
    public function up(): void
    {
        Schema::create('self_paced_learning_progress', function (Blueprint $table) {
            $table->id();

            $table->foreignId('enrollment_id')
                ->constrained('self_paced_enrollments')
                ->cascadeOnDelete();
            $table->foreignId('user_id')
                ->constrained('users')
                ->cascadeOnDelete();
            $table->foreignId('subtopic_id')
                ->constrained('self_paced_subtopics')
                ->cascadeOnDelete();
            $table->foreignId('topic_id')
                ->constrained('self_paced_topics')
                ->cascadeOnDelete();
            $table->foreignId('course_id')
                ->constrained('self_paced_courses')
                ->cascadeOnDelete();

            $table->timestamp('marked_read_at')->nullable();

            $table->timestamps();

            // A subtopic can only be marked read once per enrollment
            $table->unique(['enrollment_id', 'subtopic_id'], 'unique_enrollment_subtopic');

            $table->index('enrollment_id');
            $table->index('user_id');
            $table->index('subtopic_id');
            $table->index('topic_id');
            $table->index('course_id');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('self_paced_learning_progress');
    }
};
