<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('student_result_summaries', function (Blueprint $table) {
            $table->id();
            $table->foreignId('student_id')->constrained('students')->onDelete('cascade');
            $table->foreignId('academic_year_id')->constrained('academic_years')->onDelete('cascade');
            $table->foreignId('exam_type_id')->constrained('exam_types')->onDelete('cascade');
            $table->foreignId('classroom_id')->constrained('classrooms')->onDelete('cascade');
            $table->integer('total_marks'); // Sum of marks in all subjects
            $table->decimal('average_marks', 5, 2); // Total ÷ number of subjects
            $table->integer('total_points'); // Sum of top 7 subjects' points
            $table->string('division')->nullable(); // Based on total points
            $table->integer('rank')->nullable(); // Based on total marks or average
            $table->integer('subjects_count'); // Number of subjects taken
            $table->timestamp('computed_at')->useCurrent();
            $table->timestamps();

            $table->unique(['student_id', 'academic_year_id', 'exam_type_id'], 'unique_summary');
            $table->index(['academic_year_id', 'exam_type_id', 'rank'], 'idx_summary_year_exam_rank');
            $table->index(['classroom_id', 'academic_year_id', 'exam_type_id'], 'idx_summary_classroom_year_exam');
            $table->index(['division']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('student_result_summaries');
    }
};
