<?php

namespace Tests\Unit\Services\Scores;

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

class HomeworkScoreServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_list_includes_semester_variants(): void
    {
        $this->seedStudent(1, 'SCH1', 'Eli', 'Page');
        $this->seedStudentClass(1, 8, '2025-2026');

        DB::table('homework')->insert([
            'student_id' => 1,
            'school_id' => 'SCH1',
            'class_section_id' => 8,
            'updated_by' => 99,
            'homework_index' => 1,
            'score' => 91,
            'semester' => 'First Semester',
            'school_year' => '2025-2026',
        ]);

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

        $this->assertSame([1], $result['headers']);
        $this->assertSame(91.0, $result['students'][0]['scores'][1]);
    }

    public function test_add_column_inserts_next_index(): void
    {
        $this->seedStudent(1, 'SCH1', 'Eli', 'Page');
        $this->seedStudentClass(1, 8, '2025-2026');

        $service = new HomeworkScoreService(new ScoreTermService());

        $nextIndex = $service->addColumn(8, 'Fall', '2025-2026', 99);

        $this->assertSame(1, $nextIndex);
        $this->assertDatabaseHas('homework', [
            'student_id' => 1,
            'class_section_id' => 8,
            'homework_index' => 1,
        ]);
    }

    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([
            'student_id' => $studentId,
            'class_section_id' => $classSectionId,
            'school_year' => $schoolYear,
            'semester' => 'Fall',
            'is_event_only' => 0,
        ]);
    }
}
