<?php

namespace Tests\Feature;

use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Spatie\Permission\Models\Role;
use Tests\TestCase;

class AuthFrontendTest extends TestCase
{
    use RefreshDatabase;

    public function test_register_login_and_profile_legacy_urls(): void
    {
        Role::findOrCreate('member');

        $this->get('/login.shtml')->assertOk()->assertSee('登录');
        $this->get('/reg.shtml')->assertOk()->assertSee('注册');

        $this->post('/post.php', [
            'action' => 'register',
            'username' => 'alice',
            'email' => 'alice@example.test',
            'password' => 'secret12',
            'password_confirmation' => 'secret12',
        ])->assertRedirect('/');

        $this->assertAuthenticated();
        $this->get('/index.php?action=profile')->assertOk()->assertSee('alice');

        $this->post('/post.php', ['action' => 'logout'])->assertRedirect('/');
        $this->assertGuest();

        $this->post('/post.php', [
            'action' => 'dologin',
            'login' => 'alice',
            'password' => 'secret12',
        ])->assertRedirect('/');

        $this->assertAuthenticated();
    }

    public function test_legacy_md5_password_upgrades_on_login(): void
    {
        $user = User::factory()->create([
            'username' => 'legacy',
            'email' => 'legacy@example.test',
            'password' => Hash::make(str()->password(32)),
            'password_legacy' => md5('password'),
        ]);

        $this->post('/post.php', [
            'action' => 'dologin',
            'login' => 'legacy',
            'password' => 'password',
        ])->assertRedirect('/');

        $this->assertAuthenticatedAs($user);
        $user->refresh();
        $this->assertNull($user->password_legacy);
        $this->assertTrue(Hash::check('password', $user->password));
    }
}
