<?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('results', function (Blueprint $table) {
            $table->id();
            $table->foreignId('student_id')->constrained('students')->onDelete('cascade');
            $table->foreignId('subject_id')->constrained('subjects')->onDelete('cascade');
            $table->foreignId('classroom_id')->constrained('classrooms')->onDelete('cascade');
            $table->foreignId('academic_year_id')->constrained('academic_years')->onDelete('cascade');
            $table->foreignId('exam_type_id')->constrained('exam_types')->onDelete('cascade');
            $table->integer('marks'); // Raw marks (0-100)
            $table->string('grade')->nullable(); // A, B, C, D, F (auto-calculated)
            $table->integer('points')->nullable(); // Points based on grade (auto-calculated)
            $table->foreignId('teacher_id')->nullable()->constrained('users')->onDelete('set null');
            $table->timestamp('entered_at')->useCurrent();
            $table->timestamps();

            $table->unique(['student_id', 'subject_id', 'classroom_id', 'academic_year_id', 'exam_type_id'], 'unique_result');
            $table->index(['student_id', 'academic_year_id', 'exam_type_id']);
            $table->index(['classroom_id', 'academic_year_id', 'exam_type_id']);
            $table->index(['subject_id', 'academic_year_id', 'exam_type_id']);
            $table->index(['teacher_id']);
        });
    }

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