<?php

namespace Tests\Feature\Api\V1;

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

class PatientIsolationTest extends TestCase
{
    use RefreshDatabase;

    public function test_patient_cannot_read_or_edit_another_patient(): void
    {
        $this->seed(ClinicDemoSeeder::class);
        $patients = Patient::orderBy('id')->take(2)->get();
        $orgId = $patients[0]->organization_id;

        $user1 = User::create([
            'organization_id' => $orgId,
            'name' => 'Patient One',
            'email' => 'patient.one@example.test',
            'password' => 'password',
            'role' => UserRole::PATIENT,
            'status' => UserStatus::ACTIVE,
        ]);
        $user2 = User::create([
            'organization_id' => $orgId,
            'name' => 'Patient Two',
            'email' => 'patient.two@example.test',
            'password' => 'password',
            'role' => UserRole::PATIENT,
            'status' => UserStatus::ACTIVE,
        ]);
        $patients[0]->update(['user_id' => $user1->id]);
        $patients[1]->update(['user_id' => $user2->id]);

        Sanctum::actingAs($user1);
        $this->getJson('/api/v1/patients/'.$patients[1]->id)->assertForbidden();
        $this->patchJson('/api/v1/patients/'.$patients[1]->id, ['name' => 'Unauthorized'])->assertForbidden();
        $this->getJson('/api/v1/patients/'.$patients[0]->id)->assertOk();
    }
}
