<?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_topic_timers table — tracks elapsed seconds a
     * Trainee has spent on each Course_Topic within an Enrollment.
     */
    public function up(): void
    {
        Schema::create('self_paced_topic_timers', function (Blueprint $table) {
            $table->id();

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

            $table->unsignedInteger('elapsed_seconds')->default(0);
            $table->timestamp('last_active_at')->nullable();

            $table->timestamps();

            // One timer record per enrollment per topic
            $table->unique(['enrollment_id', 'topic_id'], 'unique_enrollment_topic_timer');

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

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