<?php

namespace Tests\Feature\Auth;

use App\Models\Otp;
use App\Models\Patient;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use Tests\TestCase;

class PatientOtpLoginTest extends TestCase
{
    use RefreshDatabase;

    public function test_patient_otp_login_screen_can_be_rendered(): void
    {
        $response = $this->get(route('patient.login'));

        $response->assertStatus(200);
    }

    public function test_patient_can_request_otp_using_email_or_phone(): void
    {
        Mail::fake();

        $patient = Patient::query()->create([
            'full_name' => 'OTP Patient',
            'email' => 'otp.patient@example.test',
            'phone' => '+2348000000111',
        ]);

        $response = $this->post(route('patient.otp.request'), [
            'identifier' => $patient->email,
        ]);

        $response->assertRedirect(route('patient.otp.verify'));
        $this->assertDatabaseHas('otps', [
            'identifier' => 'patient:'.$patient->id,
        ]);
    }

    public function test_patient_can_login_with_valid_otp_only(): void
    {
        $patient = Patient::query()->create([
            'full_name' => 'Portal Patient',
            'email' => 'portal.patient@example.test',
            'phone' => '+2348000000112',
        ]);

        $this->post(route('patient.otp.request'), [
            'identifier' => $patient->email,
        ])->assertRedirect(route('patient.otp.verify'));

        $otp = Otp::query()->latest('id')->firstOrFail();
        $otp->update([
            'code_hash' => Hash::make('123456'),
        ]);

        $verifyResponse = $this->post(route('patient.otp.verify.store'), [
            'otp' => '123456',
        ]);

        $verifyResponse->assertRedirect(route('patient.portal'));
        $this->assertAuthenticated('patient');
    }
}
