<?php

namespace Tests\Unit\Services\Attendance;

use App\Services\Attendance\AttendanceRecordSyncService;
use App\Services\Attendance\StudentAttendanceWriterService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Mockery;
use Tests\TestCase;

class StudentAttendanceWriterServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_resolve_student_school_id_from_student(): void
    {
        DB::table('students')->insert([
            'id' => 1,
            'school_id' => 'S1',
            'firstname' => 'Test',
            'lastname' => 'Student',
            'age' => 8,
            'gender' => 'Male',
            'photo_consent' => 1,
            'parent_id' => 1,
            'year_of_registration' => '2025',
            'school_year' => '2025-2026',
        ]);

        $sync = Mockery::mock(AttendanceRecordSyncService::class);
        $service = new StudentAttendanceWriterService(new \App\Models\AttendanceData(), new \App\Models\Student(), $sync);

        $this->assertSame('S1', $service->resolveStudentSchoolId(1, null));
    }

    public function test_save_or_update_updates_existing_and_syncs_record(): void
    {
        DB::table('students')->insert([
            'id' => 1,
            'school_id' => 'S1',
            'firstname' => 'Test',
            'lastname' => 'Student',
            'age' => 8,
            'gender' => 'Male',
            'photo_consent' => 1,
            'parent_id' => 1,
            'year_of_registration' => '2025',
            'school_year' => '2025-2026',
        ]);

        DB::table('attendance_data')->insert([
            'class_id' => 1,
            'class_section_id' => 1,
            'student_id' => 1,
            'school_id' => 'S1',
            'date' => '2025-01-01',
            'status' => 'present',
            'is_reported' => 'no',
            'is_notified' => 'no',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        $sync = Mockery::mock(AttendanceRecordSyncService::class);
        $sync->shouldReceive('updateAttendanceRecord')->once();

        $service = new StudentAttendanceWriterService(new \App\Models\AttendanceData(), new \App\Models\Student(), $sync);

        $service->saveOrUpdateStudentAttendance([
            'class_section_id' => 1,
            'student_id' => 1,
            'school_id' => null,
            'status' => 'absent',
            'reason' => 'Sick',
            'is_reported' => 'yes',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'date' => '2025-01-01',
            'class_id' => 1,
            'user_id' => 1,
        ]);

        $this->assertDatabaseHas('attendance_data', [
            'student_id' => 1,
            'status' => 'absent',
            'reason' => 'Sick',
            'is_reported' => 'yes',
        ]);
    }
}
