<?php

declare(strict_types=1);

namespace HyperfTest\Cases\Integration\Auth;

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

use function Hyperf\Support\make;

/**
 * ApiKeyController toggle + store 增强校验集成测试
 *
 * @internal
 * @coversNothing
 */
class ApiKeyToggleTest extends TestCase
{
    protected function createTestUser(string $suffix, array $overrides = []): User
    {
        return User::query()->create(array_merge([
            'username' => 'toggle_test_' . $suffix,
            'password' => 'Pass_' . $suffix,
            'email' => 'toggle_test_' . $suffix . '@example.com',
            'status' => 1,
            'api_key_enabled' => true,
        ], $overrides));
    }

    protected function getAuthToken(User $user): string
    {
        $auth = make(AuthManager::class);
        return $auth->guard('jwt')->login($user);
    }

    protected function authHeaders(User $user): array
    {
        return ['Authorization' => 'Bearer ' . $this->getAuthToken($user)];
    }

    public function test_user_can_toggle_own_key(): void
    {
        $user = $this->createTestUser('own_' . uniqid());
        $result = ApiKey::generate($user->id, 'Own Toggle Key');
        $key_id = $result['api_key']->id;

        // 禁用
        $response = $this->patch('/api/v1/me/api-keys/' . $key_id . '/toggle', ['enabled' => false], $this->authHeaders($user));
        $response->assertStatus(200);
        $response->assertJsonPath('code', 0);
        $body = json_decode($response->getBody()->getContents(), true);
        $this->assertFalse($body['data']['enabled']);

        // 重新启用
        $response = $this->patch('/api/v1/me/api-keys/' . $key_id . '/toggle', ['enabled' => true], $this->authHeaders($user));
        $response->assertStatus(200);
        $body = json_decode($response->getBody()->getContents(), true);
        $this->assertTrue($body['data']['enabled']);

        $user->forceDelete();
    }

    public function test_user_cannot_toggle_others_key(): void
    {
        $user_a = $this->createTestUser('a_' . uniqid());
        $user_b = $this->createTestUser('b_' . uniqid());
        $result = ApiKey::generate($user_b->id, 'Other User Key');

        $response = $this->patch('/api/v1/me/api-keys/' . $result['api_key']->id . '/toggle', ['enabled' => false], $this->authHeaders($user_a));
        $response->assertStatus(404);

        $user_a->forceDelete();
        $user_b->forceDelete();
    }

    public function test_toggle_nonexistent_key_returns_404(): void
    {
        $user = $this->createTestUser('nokey_' . uniqid());

        $response = $this->patch('/api/v1/me/api-keys/999999/toggle', ['enabled' => false], $this->authHeaders($user));
        $response->assertStatus(404);

        $user->forceDelete();
    }

    public function test_user_cannot_create_duplicate_name(): void
    {
        $user = $this->createTestUser('dup_' . uniqid());

        // 创建第一个 Key
        $response = $this->post('/api/v1/me/api-keys', ['name' => 'Duplicate Name'], $this->authHeaders($user));
        $response->assertStatus(200);

        // 创建同名 Key
        $response = $this->post('/api/v1/me/api-keys', ['name' => 'Duplicate Name'], $this->authHeaders($user));
        $response->assertStatus(400);
        $body = json_decode($response->getBody()->getContents(), true);
        $this->assertStringContainsString('已存在同名', $body['message']);

        $user->forceDelete();
    }

    public function test_user_can_reuse_name_after_delete(): void
    {
        $user = $this->createTestUser('reuse_' . uniqid());

        // 创建 Key
        $response = $this->post('/api/v1/me/api-keys', ['name' => 'Reuse Name'], $this->authHeaders($user));
        $response->assertStatus(200);
        $body = json_decode($response->getBody()->getContents(), true);
        $key_id = $body['data']['api_key']['id'];

        // 删除
        $response = $this->delete('/api/v1/me/api-keys/' . $key_id, [], $this->authHeaders($user));
        $response->assertStatus(200);

        // 复用名称创建新 Key
        $response = $this->post('/api/v1/me/api-keys', ['name' => 'Reuse Name'], $this->authHeaders($user));
        $response->assertStatus(200);

        $user->forceDelete();
    }

    public function test_user_cannot_create_more_than_10_keys(): void
    {
        $user = $this->createTestUser('limit_' . uniqid());

        // 通过模型直接创建 10 个 Key
        for ($i = 1; $i <= 10; $i++) {
            ApiKey::generate($user->id, 'Key ' . $i);
        }

        // 尝试创建第 11 个
        $response = $this->post('/api/v1/me/api-keys', ['name' => 'Key 11'], $this->authHeaders($user));
        $response->assertStatus(400);
        $body = json_decode($response->getBody()->getContents(), true);
        $this->assertStringContainsString('最多创建 10 个', $body['message']);

        $user->forceDelete();
    }

    public function test_user_can_create_after_deleting_to_below_limit(): void
    {
        $user = $this->createTestUser('dellimit_' . uniqid());

        // 创建 10 个 Key
        $results = [];
        for ($i = 1; $i <= 10; $i++) {
            $results[] = ApiKey::generate($user->id, 'Key ' . $i);
        }

        // 删除一个
        $this->delete('/api/v1/me/api-keys/' . $results[0]['api_key']->id, [], $this->authHeaders($user));

        // 现在可以创建新的
        $response = $this->post('/api/v1/me/api-keys', ['name' => 'New Key'], $this->authHeaders($user));
        $response->assertStatus(200);

        $user->forceDelete();
    }
}
