<?php

namespace Tests\Feature\Api\V1;

use App\Models\User;
use Database\Seeders\ClinicDemoSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

class PatientApiTest extends TestCase
{
    use RefreshDatabase;

    public function test_assistant_can_create_patient_and_whatsapp_defaults_to_phone(): void
    {
        $this->seed(ClinicDemoSeeder::class);
        $assistant = User::where('email', 'assistant.one@smartclinic.test')->firstOrFail();
        Sanctum::actingAs($assistant);

        $response = $this->postJson('/api/v1/patients', [
            'name' => 'New Patient',
            'phone' => '+923331112222',
            'has_whatsapp' => true,
            'email' => 'patient@example.test',
            'city' => 'Lahore',
        ]);

        $response->assertCreated()
            ->assertJsonPath('data.has_whatsapp', true)
            ->assertJsonPath('data.whatsapp', '+923331112222');

        $this->assertDatabaseHas('patients', [
            'name' => 'New Patient',
            'normalized_phone' => '+923331112222',
            'whatsapp' => '+923331112222',
        ]);
    }

    public function test_duplicate_phone_returns_domain_conflict(): void
    {
        $this->seed(ClinicDemoSeeder::class);
        $assistant = User::where('email', 'assistant.one@smartclinic.test')->firstOrFail();
        Sanctum::actingAs($assistant);

        $this->postJson('/api/v1/patients', [
            'name' => 'Duplicate',
            'phone' => '+923001234567',
            'has_whatsapp' => true,
        ])->assertStatus(409)
            ->assertJsonPath('error.code', 'PATIENT_DUPLICATE_POSSIBLE');
    }
}
