<?php

declare(strict_types=1);

namespace Tests\Feature\Account;

use App\Notifications\ResetCustomerPassword;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Password;
use Mtc\MercuryDataModels\Customer;

class PasswordResetTest extends AccountTestCase
{
    public function testSendsResetLink(): void
    {
        Notification::fake();

        $customer = Customer::create([
            'first_name' => 'Ada',
            'last_name' => 'Lovelace',
            'email' => 'ada@example.com',
            'password' => 'old-secret',
        ]);

        $response = $this->asTenant(tenant())->postJson(route('account.password.email'), [
            'email' => 'ada@example.com',
        ]);

        $response->assertStatus(200);
        Notification::assertSentTo($customer, ResetCustomerPassword::class);
    }

    public function testResetsPasswordWithValidToken(): void
    {
        $customer = Customer::create([
            'first_name' => 'Ada',
            'last_name' => 'Lovelace',
            'email' => 'ada@example.com',
            'password' => 'old-secret',
        ]);

        $token = Password::broker('customers')->createToken($customer);

        $response = $this->asTenant(tenant())->postJson(route('account.password.reset'), [
            'email' => 'ada@example.com',
            'token' => $token,
            'password' => 'brand-new-password-1',
            'password_confirmation' => 'brand-new-password-1',
        ]);

        $response->assertStatus(200);

        $refreshed = $customer->fresh();
        $this->assertTrue(password_verify('brand-new-password-1', $refreshed->password));
    }

    public function testRejectsInvalidToken(): void
    {
        Customer::create([
            'first_name' => 'Ada',
            'last_name' => 'Lovelace',
            'email' => 'ada@example.com',
            'password' => 'old-secret',
        ]);

        $response = $this->asTenant(tenant())->postJson(route('account.password.reset'), [
            'email' => 'ada@example.com',
            'token' => 'not-a-real-token',
            'password' => 'brand-new-password-1',
            'password_confirmation' => 'brand-new-password-1',
        ]);

        $response->assertStatus(422);
    }
}
