<?php

namespace Tests\Feature;

use App\Models\Company;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class ApiPasswordResetTest extends TestCase
{
    use RefreshDatabase;

    public function test_forgot_password_returns_generic_success_message(): void
    {
        $company = Company::query()->create([
            'name' => 'Reset Co',
            'short_name' => 'resetco',
            'status' => 'active',
        ]);
        User::factory()->create([
            'email' => 'reset-me@example.com',
            'company_id' => $company->id,
            'allow_login' => true,
        ]);

        $response = $this->postJson('/api/auth/forgot-password', [
            'company' => 'resetco',
            'email' => 'reset-me@example.com',
        ]);

        $response->assertOk();
        $response->assertJsonFragment([
            'message' => 'If an account exists for that address, a password reset link has been sent.',
        ]);
    }

    public function test_reset_password_updates_credentials_and_revokes_tokens(): void
    {
        $company = Company::query()->create([
            'name' => 'Reset Co',
            'short_name' => 'resetco',
            'status' => 'active',
        ]);
        $user = User::factory()->create([
            'email' => 'reset-done@example.com',
            'company_id' => $company->id,
            'password' => bcrypt('old-password'),
            'allow_login' => true,
        ]);

        $oldToken = $user->createToken('api')->plainTextToken;
        $token = \Illuminate\Support\Facades\Password::createToken($user);

        $response = $this->postJson('/api/auth/reset-password', [
            'company' => 'resetco',
            'email' => 'reset-done@example.com',
            'token' => $token,
            'password' => 'new-password-12',
            'password_confirmation' => 'new-password-12',
        ]);

        $response->assertOk();

        $this->assertTrue(\Illuminate\Support\Facades\Hash::check('new-password-12', $user->fresh()->password));

        $this->withHeader('Authorization', 'Bearer '.$oldToken)
            ->getJson('/api/auth/user')
            ->assertUnauthorized();
    }
}
