<?php

namespace Tests\Feature\Api\V1\Utilities;

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

class PhoneFormatterControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_format_returns_formatted_phone(): void
    {
        $user = $this->createUser();
        Sanctum::actingAs($user);

        $response = $this->postJson('/api/v1/utilities/phone/format', [
            'number' => '(555) 123-4567',
        ]);

        $response->assertOk();
        $response->assertJsonPath('data.phone.formatted', '555-123-4567');
        $response->assertJsonPath('data.phone.is_valid', true);
    }

    public function test_format_rejects_invalid_number(): void
    {
        $user = $this->createUser();
        Sanctum::actingAs($user);

        $response = $this->postJson('/api/v1/utilities/phone/format', [
            'number' => '123',
        ]);

        $response->assertStatus(422);
    }

    public function test_format_validates_payload(): void
    {
        $user = $this->createUser();
        Sanctum::actingAs($user);

        $response = $this->postJson('/api/v1/utilities/phone/format', []);

        $response->assertStatus(422);
        $response->assertJsonStructure(['message', 'errors']);
    }

    private function createUser(): User
    {
        $roleId = DB::table('roles')->insertGetId([
            'name' => 'admin',
            'priority' => 1,
            'is_active' => 1,
        ]);

        $user = User::query()->create([
            'firstname' => 'Test',
            'lastname' => 'User',
            'email' => 'admin@example.com',
            'cellphone' => '5555555555',
            'address_street' => '123 Main',
            'city' => 'City',
            'state' => 'ST',
            'zip' => '12345',
            'accept_school_policy' => 1,
            'status' => 'Active',
            'password' => bcrypt('secret'),
            'semester' => 'Fall',
            'school_year' => '2025-2026',
        ]);

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

        return $user;
    }
}
