<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Modules\Results\Models\Result;
use Modules\Results\Services\ResultCalculationService;

class CalculateResultSummaries extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'results:calculate-summaries';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Calculate missing student result summaries';

    /**
     * Execute the console command.
     */
    public function handle()
    {
        $this->info('Calculating missing student result summaries...');

        $calculationService = app(ResultCalculationService::class);

        // Get all unique student-academic_year-exam_type combinations
        $combinations = Result::select('student_id', 'academic_year_id', 'exam_type_id')
            ->distinct()
            ->get();

        $this->info("Found {$combinations->count()} unique student-exam combinations");

        $successCount = 0;
        $errorCount = 0;

        $progressBar = $this->output->createProgressBar($combinations->count());
        $progressBar->start();

        foreach ($combinations as $combination) {
            try {
                $calculationService->calculateStudentSummary(
                    $combination->student_id,
                    $combination->academic_year_id,
                    $combination->exam_type_id
                );
                $successCount++;
            } catch (\Exception $e) {
                $errorCount++;
                $this->error("Error for student {$combination->student_id}: " . $e->getMessage());
            }

            $progressBar->advance();
        }

        $progressBar->finish();
        $this->newLine();

        $this->info("Summary calculation completed!");
        $this->info("Successfully calculated: {$successCount}");
        $this->info("Errors: {$errorCount}");

        // Now recalculate all ranks
        $this->info("Recalculating ranks...");

        $classroomExamCombinations = \Modules\Results\Models\StudentResultSummary::select('classroom_id', 'academic_year_id', 'exam_type_id')
            ->distinct()
            ->get();

        $rankProgressBar = $this->output->createProgressBar($classroomExamCombinations->count());
        $rankProgressBar->start();

        foreach ($classroomExamCombinations as $combination) {
            $calculationService->recalculateClassroomRanks(
                $combination->classroom_id,
                $combination->academic_year_id,
                $combination->exam_type_id
            );
            $rankProgressBar->advance();
        }

        $rankProgressBar->finish();
        $this->newLine();
        $this->info("Rank recalculation completed!");

        return Command::SUCCESS;
    }
}
