<?php

declare(strict_types=1);

namespace HyperfTest\Cases\Integration\User;

use App\Model\Role;
use App\Model\User;
use HyperfTest\TestCase;
use Qbhy\HyperfAuth\AuthManager;

use function Hyperf\Support\make;

/**
 * UserController::updateApiKeyEnabled 集成测试
 *
 * @internal
 * @coversNothing
 */
class UserApiKeyEnabledTest extends TestCase
{
    protected function getAdminAuthToken(): string
    {
        $admin_role = $this->fetchAdminRole();
        $user = User::query()
            ->where('status', 1)
            ->where('role_id', $admin_role->id)
            ->first();
        if (!$user) {
            $this->markTestSkipped('没有可用的 administrator 用户，无法测试');
        }

        $auth = make(AuthManager::class);
        return $auth->guard('jwt')->login($user);
    }

    protected function fetchAdminRole(): Role
    {
        return Role::query()->where('name', 'administrator')->firstOrFail();
    }

    protected function adminHeaders(): array
    {
        return ['Authorization' => 'Bearer ' . $this->getAdminAuthToken()];
    }

    protected function createTestUser(string $suffix, array $overrides = []): User
    {
        return User::query()->create(array_merge([
            'username' => 'ake_test_' . $suffix,
            'password' => 'Pass_' . $suffix,
            'email' => 'ake_test_' . $suffix . '@example.com',
            'status' => 1,
            'api_key_enabled' => true,
        ], $overrides));
    }

    protected function getNonAdminHeaders(): array
    {
        $user = $this->createTestUser('nonadmin_' . uniqid());
        $auth = make(AuthManager::class);
        $token = $auth->guard('jwt')->login($user);
        return ['Authorization' => 'Bearer ' . $token];
    }

    public function test_admin_can_enable_user_api_key(): void
    {
        $user = $this->createTestUser('enable_' . uniqid(), ['api_key_enabled' => false]);

        $response = $this->patch('/api/v1/users/' . $user->id . '/api-key-enabled', ['api_key_enabled' => true], $this->adminHeaders());

        $response->assertStatus(200);
        $response->assertJsonPath('code', 0);
        $body = json_decode($response->getBody()->getContents(), true);
        $this->assertTrue($body['data']['api_key_enabled']);
        $this->assertEquals($user->username, $body['data']['username']);

        $user->forceDelete();
    }

    public function test_admin_can_disable_user_api_key(): void
    {
        $user = $this->createTestUser('disable_' . uniqid(), ['api_key_enabled' => true]);

        $response = $this->patch('/api/v1/users/' . $user->id . '/api-key-enabled', ['api_key_enabled' => false], $this->adminHeaders());

        $response->assertStatus(200);
        $body = json_decode($response->getBody()->getContents(), true);
        $this->assertFalse($body['data']['api_key_enabled']);

        $user->forceDelete();
    }

    public function test_non_admin_cannot_update_api_key_enabled(): void
    {
        $target = $this->createTestUser('target_' . uniqid());
        $headers = $this->getNonAdminHeaders();

        $response = $this->patch('/api/v1/users/' . $target->id . '/api-key-enabled', ['api_key_enabled' => false], $headers);

        $response->assertStatus(403);

        $target->forceDelete();
    }

    public function test_update_nonexistent_user_returns_404(): void
    {
        $response = $this->patch('/api/v1/users/999999/api-key-enabled', ['api_key_enabled' => false], $this->adminHeaders());

        $response->assertStatus(404);
    }
}
