<?php

namespace Tests\Unit\Services\Scores;

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

class ScoreCommentServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_list_returns_comments_for_students(): void
    {
        $this->seedStudent(1, 'SCH1', 'Ava', 'Lane');
        $this->seedStudentClass(1, 2, '2025-2026');

        DB::table('score_comments')->insert([
            'student_id' => 1,
            'class_section_id' => 2,
            'score_type' => 'midterm',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'comment' => 'Ava has shown consistent improvement and strong effort across assignments.',
        ]);

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

        $this->assertCount(1, $result['students']);
        $this->assertSame('Ava', $result['students'][0]['firstname']);
        $this->assertSame('midterm', array_key_first($result['comments'][1]));
    }

    public function test_save_returns_validation_errors_for_short_comment(): void
    {
        $this->seedStudent(1, 'SCH1', 'Ava', 'Lane');

        $service = new ScoreCommentService(new ScoreTermService());
        $result = $service->save(
            2,
            'Fall',
            '2025-2026',
            [1 => ['midterm' => 'Too short']],
            [],
            99
        );

        $this->assertNotEmpty($result['errors']);
    }

    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' => 'F',
            '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,
        ]);
    }
}
