<?php

namespace Tests\Feature\Api\V1\Teachers;

use App\Models\User;
use Carbon\Carbon;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

class TeacherControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_classes_returns_students_and_assignments(): void
    {
        $this->seedConfig();
        $teacher = $this->seedTeacherUser();
        $classSectionId = $this->seedClassSection();
        $this->seedTeacherAssignment($teacher->id, $classSectionId);
        $this->seedStudent($teacher->id, $classSectionId);

        Sanctum::actingAs($teacher);
        $response = $this->getJson('/api/v1/teachers/classes?class_section_id=' . $classSectionId);

        $response->assertOk();
        $response->assertJson(['ok' => true]);
        $this->assertNotEmpty($response->json('students'));
        $this->assertSame($classSectionId, $response->json('active_class_section_id'));
    }

    public function test_switch_class_returns_active_id(): void
    {
        $this->seedConfig();
        $teacher = $this->seedTeacherUser();
        $classSectionId = $this->seedClassSection();
        $this->seedTeacherAssignment($teacher->id, $classSectionId);

        Sanctum::actingAs($teacher);
        $response = $this->postJson('/api/v1/teachers/classes/switch', [
            'class_section_id' => $classSectionId,
        ]);

        $response->assertOk();
        $response->assertJsonPath('active_class_section_id', $classSectionId);
    }

    public function test_absence_submit_creates_staff_attendance(): void
    {
        Carbon::setTestNow(Carbon::parse('2025-10-01'));
        $this->seedConfig();
        $teacher = $this->seedTeacherUser();

        Sanctum::actingAs($teacher);
        $formResponse = $this->getJson('/api/v1/teachers/absence/form');

        $formResponse->assertOk();
        $date = $formResponse->json('available_dates.0');

        $response = $this->postJson('/api/v1/teachers/absence', [
            'dates' => [$date],
            'reason' => 'Family event',
            'reason_type' => 'personal',
        ]);

        $response->assertOk();
        $this->assertDatabaseHas('staff_attendance', [
            'user_id' => $teacher->id,
            'date' => $date,
            'status' => 'absent',
        ]);
        Carbon::setTestNow();
    }

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

    private function seedTeacherUser(): User
    {
        $roleId = DB::table('roles')->insertGetId([
            'name' => 'teacher',
        ]);

        $userId = DB::table('users')->insertGetId([
            'firstname' => 'Tara',
            'lastname' => 'Teacher',
            'cellphone' => '4444444444',
            'email' => 'teacher.feature@example.com',
            'address_street' => '123 Street',
            'city' => 'City',
            'state' => 'ST',
            'zip' => '12345',
            'accept_school_policy' => 1,
            'password' => bcrypt('password'),
            'user_type' => 'primary',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'status' => 'Active',
        ]);

        DB::table('user_roles')->insert([
            'user_id' => $userId,
            'role_id' => $roleId,
        ]);

        return User::query()->findOrFail($userId);
    }

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

        return 301;
    }

    private function seedTeacherAssignment(int $teacherId, int $classSectionId): void
    {
        DB::table('teacher_class')->insert([
            'teacher_id' => $teacherId,
            'class_section_id' => $classSectionId,
            'position' => 'main',
            'school_year' => '2025-2026',
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

    private function seedStudent(int $parentId, int $classSectionId): void
    {
        $studentId = DB::table('students')->insertGetId([
            'school_id' => 'S-600',
            'firstname' => 'Kai',
            'lastname' => 'Student',
            'dob' => '2014-09-01',
            'age' => 11,
            'gender' => 'Male',
            'photo_consent' => 1,
            'parent_id' => $parentId,
            'year_of_registration' => '2025',
            'school_year' => '2025-2026',
            'semester' => 'Fall',
        ]);

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