<?php

declare(strict_types=1);

namespace Tests\Feature;

use App\Models\QuestionBank;
use App\Models\SchoolClass;
use App\Models\User;
use App\Services\QuestionImportService;
use App\Services\QuizService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Str;
use Tests\TestCase;
use Tymon\JWTAuth\Facades\JWTAuth;

final class ReportTest extends TestCase
{
    use RefreshDatabase;

    protected bool $seed = true;

    public function test_reports_include_class_ranking_and_mastery(): void
    {
        $teacher = User::factory()->create(['role' => 'teacher']);
        $student = User::factory()->create(['role' => 'user']);
        $class = SchoolClass::create([
            'owner_id' => $teacher->id,
            'name' => '一班',
            'join_code' => strtoupper(Str::random(8)),
            'is_active' => true,
        ]);
        $class->members()->attach($student->id, ['role' => 'student']);

        $bank = QuestionBank::create([
            'owner_id' => $teacher->id,
            'name' => '报表题库',
            'visibility' => 'public',
            'is_active' => true,
        ]);
        app(QuestionImportService::class)->importJsonText($bank, $teacher, file_get_contents(base_path('question.json')));

        $service = app(QuizService::class);
        $attempt = $service->startPractice($student, $bank, 'practice', ['limit' => 1]);
        $item = $attempt->items()->with('question.options')->firstOrFail();
        $correctOptionIds = $item->question->options->where('is_correct', true)->pluck('id')->all();
        $service->answer($student, $attempt, $item->question_id, $correctOptionIds);
        $service->submit($student, $attempt);

        $this->withToken(JWTAuth::fromUser($teacher))
            ->getJson('/api/admin/reports/class-ranking')
            ->assertOk()
            ->assertJsonPath('data.0.name', '一班')
            ->assertJsonPath('data.0.attempts', 1)
            ->assertJsonPath('data.0.accuracy', 100);

        $this->withToken(JWTAuth::fromUser($teacher))
            ->getJson('/api/admin/reports/mastery')
            ->assertOk()
            ->assertJsonPath('data.banks.0.name', '报表题库')
            ->assertJsonPath('data.banks.0.accuracy', 100);
    }
}
