<?php

namespace Tests\Unit\Services\Students;

use App\Services\Students\StudentAssignmentService;
use App\Services\Students\StudentConfigService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class StudentAssignmentServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_assign_creates_student_class_rows(): void
    {
        $this->seedConfig();
        $studentId = $this->seedStudent();
        $classSectionId = $this->seedClassSection();

        $service = new StudentAssignmentService(new StudentConfigService());
        $result = $service->assignClasses($studentId, [$classSectionId], false);

        $this->assertTrue($result['ok']);
        $this->assertDatabaseHas('student_class', [
            'student_id' => $studentId,
            'class_section_id' => $classSectionId,
            'school_year' => '2025-2026',
        ]);
    }

    public function test_remove_deletes_assignment(): void
    {
        $this->seedConfig();
        $studentId = $this->seedStudent();
        $classSectionId = $this->seedClassSection();

        DB::table('student_class')->insert([
            'student_id' => $studentId,
            'class_section_id' => $classSectionId,
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        $service = new StudentAssignmentService(new StudentConfigService());
        $result = $service->removeClass($studentId, $classSectionId);

        $this->assertTrue($result['ok']);
        $this->assertDatabaseMissing('student_class', [
            'student_id' => $studentId,
            'class_section_id' => $classSectionId,
            'school_year' => '2025-2026',
        ]);
    }

    private function seedConfig(): void
    {
        DB::table('configuration')->insert([
            ['config_key' => 'school_year', 'config_value' => '2025-2026'],
            ['config_key' => 'semester', 'config_value' => 'Fall'],
        ]);
    }

    private function seedStudent(): int
    {
        return DB::table('students')->insertGetId([
            'school_id' => 'S-700',
            'firstname' => 'Mina',
            'lastname' => 'Student',
            'dob' => '2014-09-01',
            'age' => 11,
            'gender' => 'Female',
            'photo_consent' => 1,
            'parent_id' => 1,
            'year_of_registration' => '2025',
            'school_year' => '2025-2026',
            'semester' => 'Fall',
        ]);
    }

    private function seedClassSection(): int
    {
        DB::table('classSection')->insert([
            'class_id' => 1,
            'class_section_id' => 501,
            'class_section_name' => '5A',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        return 501;
    }
}
