<?php

namespace Tests\Unit\Services\EmergencyContacts;

use App\Models\EmergencyContact;
use App\Models\Student;
use App\Models\User;
use App\Services\EmergencyContacts\EmergencyContactDirectoryService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class EmergencyContactDirectoryServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_groups_include_parent_students_contacts_and_phones(): void
    {
        $parent = User::factory()->create([
            'firstname' => 'Salma',
            'lastname' => 'Parent',
            'cellphone' => '1111111111',
        ]);

        DB::table('parents')->insert([
            'secondparent_firstname' => 'Hadi',
            'secondparent_lastname' => 'Parent',
            'secondparent_gender' => 'Male',
            'secondparent_email' => 'second.parent@example.com',
            'secondparent_phone' => '2222222222',
            'firstparent_id' => $parent->id,
            'secondparent_id' => 999,
            'semester' => 'Fall',
            'school_year' => '2025-2026',
            'created_at' => now(),
            'updated_at' => now(),
        ]);

        Student::factory()->create([
            'parent_id' => $parent->id,
            'firstname' => 'Layla',
            'lastname' => 'Student',
            'school_id' => 'S-101',
        ]);

        EmergencyContact::query()->create([
            'parent_id' => $parent->id,
            'emergency_contact_name' => 'Aunt Sara',
            'cellphone' => '3333333333',
            'email' => 'sara@example.com',
            'relation' => 'Aunt',
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

        $service = app(EmergencyContactDirectoryService::class);
        $groups = $service->groups();

        $this->assertCount(1, $groups);
        $group = $groups[0];

        $this->assertSame($parent->id, $group['parent_id']);
        $this->assertSame('Salma Parent', $group['parent_name']);
        $this->assertSame(['1111111111', '2222222222'], $group['parent_phones']);
        $this->assertNotEmpty($group['students']);
        $this->assertNotEmpty($group['contacts']);
    }
}
