<?php

namespace Tests\Unit\Services\Parents;

use App\Services\Parents\ParentConfigService;
use App\Services\Parents\ParentRegistrationService;
use App\Services\SchoolIdService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\DB;
use Tests\TestCase;

class ParentRegistrationServiceTest extends TestCase
{
    use RefreshDatabase;

    public function test_register_creates_student_and_contact(): void
    {
        $this->seedConfig();
        $parentId = $this->seedParent();

        $service = new ParentRegistrationService(new ParentConfigService(), new SchoolIdService());
        $result = $service->register($parentId, [
            [
                'firstname' => 'Omar',
                'lastname' => 'Parent',
                'dob' => '2015-06-01',
                'gender' => 'Male',
                'registration_grade' => '3',
                'photo_consent' => true,
                'is_new' => true,
                'allergies' => ['Eggs'],
                'medical_conditions' => ['Asthma'],
            ],
        ], [
            [
                'name' => 'Nora Parent',
                'cellphone' => '1234567890',
                'email' => 'nora@example.com',
                'relation' => 'Mother',
            ],
        ]);

        $this->assertNotEmpty($result['created_student_ids']);
        $this->assertDatabaseHas('students', ['firstname' => 'Omar', 'parent_id' => $parentId]);
        $this->assertDatabaseHas('emergency_contacts', ['parent_id' => $parentId, 'emergency_contact_name' => 'Nora Parent']);
    }

    private function seedParent(): int
    {
        return DB::table('users')->insertGetId([
            'firstname' => 'Parent',
            'lastname' => 'User',
            'cellphone' => '1234567890',
            'email' => 'parent4@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',
        ]);
    }

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