<?php

namespace Database\Seeders;

use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
use Modules\Results\Models\Result;
use Modules\Students\Models\Student;
use Modules\Academic\Models\Subject;
use Modules\Academic\Models\AcademicYear;
use Modules\Academic\Models\ExamType;
use Modules\Academic\Models\Classroom;
use Modules\Configuration\Models\GradingRule;

class SampleResultsSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $this->command->info('🎯 Creating sample results with new grading system...');

        // Get necessary data
        $students = Student::with('enrollments.classroom')->get();
        $subjects = Subject::all();
        $academicYears = AcademicYear::all();
        $examTypes = ExamType::all();

        if ($students->isEmpty() || $subjects->isEmpty() || $academicYears->isEmpty() || $examTypes->isEmpty()) {
            $this->command->error('❌ Missing required data. Please ensure students, subjects, academic years, and exam types exist.');
            return;
        }

        $this->command->info("📊 Found {$students->count()} students, {$subjects->count()} subjects, {$academicYears->count()} academic years, {$examTypes->count()} exam types");

        $resultCount = 0;

        foreach ($students as $student) {
            foreach ($student->enrollments as $enrollment) {
                // Get exam types for this specific academic year only
                $academicYearExamTypes = $examTypes->where('academic_year_id', $enrollment->academic_year_id);

                foreach ($academicYearExamTypes as $examType) {
                    // Create results for 6-8 random subjects per student per exam
                    $subjectCount = rand(6, 8);
                    $randomSubjects = $subjects->random($subjectCount);

                    foreach ($randomSubjects as $subject) {
                        // Check if result already exists to prevent duplicates
                        $existingResult = Result::where([
                            'student_id' => $student->id,
                            'subject_id' => $subject->id,
                            'academic_year_id' => $enrollment->academic_year_id,
                            'exam_type_id' => $examType->id,
                        ])->first();

                        if ($existingResult) {
                            continue; // Skip if result already exists
                        }

                        $marks = $this->generateRealisticMarks();

                        Result::create([
                            'student_id' => $student->id,
                            'subject_id' => $subject->id,
                            'classroom_id' => $enrollment->classroom_id,
                            'academic_year_id' => $enrollment->academic_year_id,
                            'exam_type_id' => $examType->id,
                            'marks' => $marks,
                            'teacher_id' => 1, // Assuming admin user exists
                            'entered_at' => now(),
                        ]);

                        $resultCount++;
                    }
                }
            }
        }

        $this->command->info("✅ Created {$resultCount} sample results");
    }

    /**
     * Generate realistic marks distribution
     */
    private function generateRealisticMarks(): int
    {
        $rand = rand(1, 100);

        // Distribution to create realistic grade spread
        if ($rand <= 10) {
            return rand(85, 100); // A grade (10%)
        } elseif ($rand <= 25) {
            return rand(65, 84); // B grade (15%)
        } elseif ($rand <= 50) {
            return rand(45, 64); // C grade (25%)
        } elseif ($rand <= 80) {
            return rand(25, 44); // D grade (30%)
        } else {
            return rand(0, 24); // F grade (20%)
        }
    }
}
