<?php

namespace Tests\Feature;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Tests\TestCase;

class ResetPasswordTest extends TestCase
{
    use RefreshDatabase;

    public function test_reset_password_with_valid_token_updates_password_and_revokes_tokens(): void
    {
        $user = User::factory()->create(['password' => Hash::make('password-lama')]);
        $user->createToken('existing-session');

        $token = Password::createToken($user);

        $response = $this->postJson('/api/auth/reset-password', [
            'token'                 => $token,
            'email'                 => $user->email,
            'password'              => 'password-baru',
            'password_confirmation' => 'password-baru',
        ]);

        $response->assertStatus(200)
            ->assertJson(['message' => 'Password berhasil diubah. Silakan masuk dengan password baru.']);

        $user->refresh();
        $this->assertTrue(Hash::check('password-baru', $user->password));
        $this->assertSame(0, $user->tokens()->count());
    }

    public function test_reset_password_with_invalid_token_fails(): void
    {
        $user = User::factory()->create();

        $response = $this->postJson('/api/auth/reset-password', [
            'token'                 => 'token-salah',
            'email'                 => $user->email,
            'password'              => 'password-baru',
            'password_confirmation' => 'password-baru',
        ]);

        $response->assertStatus(422)
            ->assertJson(['message' => 'Link reset password tidak valid atau sudah kedaluwarsa.']);
    }

    public function test_reset_password_requires_minimum_length_password(): void
    {
        $user  = User::factory()->create();
        $token = Password::createToken($user);

        $response = $this->postJson('/api/auth/reset-password', [
            'token'                 => $token,
            'email'                 => $user->email,
            'password'              => '123',
            'password_confirmation' => '123',
        ]);

        $response->assertStatus(422)
            ->assertJsonValidationErrors('password');
    }
}
