<?php

namespace Tests\Unit\Services\Scores;

use App\Services\Scores\ParticipationScoreService;
use App\Services\Scores\ScoreTermService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class ParticipationScoreServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_list_returns_participation_scores(): void
    {
        $this->seedStudent(1, 'SCH1', 'Owen', 'Hall');
        $this->seedStudentClass(1, 9, '2025-2026');

        DB::table('participation')->insert([
            'id' => 1,
            'student_id' => 1,
            'school_id' => 'SCH1',
            'class_section_id' => 9,
            'updated_by' => 99,
            'score' => 87,
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        $service = new ParticipationScoreService(new ScoreTermService());
        $result = $service->list(9, 'Fall', '2025-2026');

        $this->assertSame(87.0, $result['students'][0]['scores']['score']);
    }

    public function test_update_updates_existing_scores(): void
    {
        $this->seedStudent(1, 'SCH1', 'Owen', 'Hall');
        $this->seedStudentClass(1, 9, '2025-2026');

        DB::table('participation')->insert([
            'id' => 1,
            'student_id' => 1,
            'school_id' => 'SCH1',
            'class_section_id' => 9,
            'updated_by' => 99,
            'score' => 70,
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        $service = new ParticipationScoreService(new ScoreTermService());
        $count = $service->update(
            9,
            'Fall',
            '2025-2026',
            [1 => ['score' => 92]],
            [],
            99
        );

        $this->assertSame(1, $count);
        $this->assertDatabaseHas('participation', [
            'id' => 1,
            'student_id' => 1,
            'score' => 92.0,
        ]);
    }

    private function seedStudent(int $id, string $schoolId, string $first, string $last): void
    {
        DB::table('students')->insert([
            'id' => $id,
            'school_id' => $schoolId,
            'firstname' => $first,
            'lastname' => $last,
            'age' => 10,
            'gender' => 'M',
            'photo_consent' => 1,
            'parent_id' => 1,
            'year_of_registration' => '2025',
            'is_active' => 1,
        ]);
    }

    private function seedStudentClass(int $studentId, int $classSectionId, string $schoolYear): void
    {
        DB::table('student_class')->insert([
            'id' => 1,
            'student_id' => $studentId,
            'class_section_id' => $classSectionId,
            'school_year' => $schoolYear,
            'semester' => 'Fall',
            'is_event_only' => 0,
        ]);
    }
}
