<?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;

/**
 * @internal
 * @coversNothing
 */
class UserControllerTest extends TestCase
{
    /**
     * 获取认证用的 JWT Token（使用 administrator 角色用户）
     */
    protected function getAuthToken(): string
    {
        $admin_role = $this->fetchAdminRole();
        $user = $this->fetchUser(static function ($query) use ($admin_role): void {
            $query->where('status', 1)->where('role_id', $admin_role->id);
        });
        if (!$user) {
            $this->markTestSkipped('没有可用的 administrator 用户，无法测试');
        }

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

    protected function fetchAdminRole(): Role
    {
        if (\Swoole\Coroutine::getCid() > 0) {
            return Role::query()->where('name', 'administrator')->firstOrFail();
        }

        $role = null;
        \Swoole\Coroutine\run(static function () use (&$role): void {
            $role = Role::query()->where('name', 'administrator')->firstOrFail();
        });

        return $role;
    }

    /**
     * 获取认证请求头
     */
    protected function authHeaders(): array
    {
        return ['Authorization' => 'Bearer ' . $this->getAuthToken()];
    }

    protected function fetchUser(?callable $callback = null): ?User
    {
        if (\Swoole\Coroutine::getCid() > 0) {
            $query = User::query();
            if ($callback !== null) {
                $callback($query);
            }

            return $query->first();
        }

        $user = null;

        \Swoole\Coroutine\run(static function () use ($callback, &$user): void {
            $query = User::query();
            if ($callback !== null) {
                $callback($query);
            }

            $user = $query->first();
        });

        return $user;
    }

    protected function makeUserPayload(array $overrides = []): array
    {
        $suffix = bin2hex(random_bytes(4));

        return array_merge([
            'username' => 'user_' . $suffix,
            'password' => 'Pass_' . $suffix,
            'email' => 'user_' . $suffix . '@example.com',
            'status' => 1,
        ], $overrides);
    }

    protected function createUser(array $overrides = []): User
    {
        $payload = $this->makeUserPayload($overrides);

        return User::query()->create($payload);
    }

    // ========== 列表接口测试 ==========

    public function test_list_users_returns_paginated_data(): void
    {
        $response = $this->get('/api/v1/users', [], $this->authHeaders());

        $response->assertStatus(200);
        $response->assertJsonPath('code', 0);
        $response->assertJsonStructure([
            'code',
            'message',
            'data' => [
                'items',
                'total',
                'page',
                'per_page',
            ],
        ]);
    }

    public function test_list_users_respects_page_and_per_page(): void
    {
        $response = $this->get('/api/v1/users', ['page' => 1, 'per_page' => 5], $this->authHeaders());

        $response->assertStatus(200);
        $response->assertJsonPath('code', 0);
        $response->assertJsonPath('data.page', 1);
        $response->assertJsonPath('data.per_page', 5);
    }

    public function test_list_users_per_page_max_100(): void
    {
        $response = $this->get('/api/v1/users', ['per_page' => 999], $this->authHeaders());

        $response->assertStatus(200);
        $response->assertJsonPath('data.per_page', 100);
    }

    public function test_list_users_filter_by_username(): void
    {
        // 先获取一个已知用户名
        $user = $this->fetchUser();
        if (!$user) {
            $this->markTestSkipped('没有用户数据');
        }

        $response = $this->get('/api/v1/users', ['username' => $user->username], $this->authHeaders());

        $response->assertStatus(200);
        $response->assertJsonPath('code', 0);

        $body = json_decode($response->getContent(), true);
        $this->assertGreaterThanOrEqual(1, $body['data']['total']);
    }

    public function test_list_users_filter_by_email(): void
    {
        $user = $this->fetchUser(static function ($query): void {
            $query->whereNotNull('email')
                ->where('email', '!=', '');
        });
        if (!$user) {
            $this->markTestSkipped('没有用户邮箱数据');
        }

        $response = $this->get('/api/v1/users', ['email' => $user->email], $this->authHeaders());

        $response->assertStatus(200);
        $response->assertJsonPath('code', 0);

        $body = json_decode($response->getContent(), true);
        $this->assertGreaterThanOrEqual(1, $body['data']['total']);
    }

    public function test_list_users_filter_by_status(): void
    {
        $response = $this->get('/api/v1/users', ['status' => 1], $this->authHeaders());

        $response->assertStatus(200);
        $response->assertJsonPath('code', 0);

        $body = json_decode($response->getContent(), true);
        foreach ($body['data']['items'] as $item) {
            $this->assertSame(1, $item['status']);
        }
    }

    public function test_list_users_does_not_expose_password(): void
    {
        $response = $this->get('/api/v1/users', [], $this->authHeaders());

        $response->assertStatus(200);
        $body = json_decode($response->getContent(), true);

        if (!empty($body['data']['items'])) {
            $first_item = $body['data']['items'][0];
            $this->assertArrayNotHasKey('password', $first_item);
            $this->assertArrayNotHasKey('refresh_token', $first_item);
        }
    }

    public function test_list_users_filter_by_role_id(): void
    {
        $admin_role = $this->fetchAdminRole();

        $response = $this->get('/api/v1/users', ['role_id' => $admin_role->id], $this->authHeaders());

        $response->assertStatus(200);
        $response->assertJsonPath('code', 0);

        $body = json_decode($response->getContent(), true);
        $this->assertGreaterThanOrEqual(1, $body['data']['total']);
        foreach ($body['data']['items'] as $item) {
            $this->assertSame($admin_role->id, $item['role_id']);
        }
    }

    public function test_list_users_filter_by_role_id_empty(): void
    {
        $response = $this->get('/api/v1/users', ['role_id' => 999999], $this->authHeaders());

        $response->assertStatus(200);
        $response->assertJsonPath('code', 0);
        $response->assertJsonPath('data.total', 0);
    }

    // ========== 详情接口测试 ==========

    public function test_show_user_returns_user_data(): void
    {
        $user = $this->fetchUser();
        if (!$user) {
            $this->markTestSkipped('没有用户数据');
        }

        $response = $this->get('/api/v1/users/' . $user->id, [], $this->authHeaders());

        $response->assertStatus(200);
        $response->assertJsonPath('code', 0);
        $response->assertJsonPath('data.id', $user->id);
        $response->assertJsonPath('data.username', $user->username);
    }

    public function test_show_user_does_not_expose_password(): void
    {
        $user = $this->fetchUser();
        if (!$user) {
            $this->markTestSkipped('没有用户数据');
        }

        $response = $this->get('/api/v1/users/' . $user->id, [], $this->authHeaders());

        $response->assertStatus(200);
        $body = json_decode($response->getContent(), true);
        $this->assertArrayNotHasKey('password', $body['data']);
        $this->assertArrayNotHasKey('refresh_token', $body['data']);
    }

    public function test_show_user_not_found_returns_404(): void
    {
        $response = $this->get('/api/v1/users/999999', [], $this->authHeaders());

        $response->assertStatus(404);
        $response->assertJsonPath('code', 404);
    }

    // ========== 创建接口测试 ==========

    public function test_create_user_success(): void
    {
        $payload = $this->makeUserPayload();

        $response = $this->post('/api/v1/users', $payload, $this->authHeaders());

        $response->assertStatus(200);
        $response->assertJsonPath('code', 0);
        $response->assertJsonPath('data.username', $payload['username']);
        $response->assertJsonPath('data.email', $payload['email']);
        $response->assertJsonPath('data.status', 1);
    }

    public function test_create_user_validation_error_returns_400(): void
    {
        $payload = $this->makeUserPayload([
            'username' => 'ab',
        ]);

        $response = $this->post('/api/v1/users', $payload, $this->authHeaders());

        $response->assertStatus(400);
        $response->assertJsonPath('code', 400);
    }

    public function test_create_user_duplicate_username_returns_400(): void
    {
        $user = $this->createUser();

        $payload = $this->makeUserPayload([
            'username' => $user->username,
        ]);

        $response = $this->post('/api/v1/users', $payload, $this->authHeaders());

        $response->assertStatus(400);
        $response->assertJsonPath('code', 400);
    }

    public function test_create_user_duplicate_email_returns_400(): void
    {
        $user = $this->createUser();

        $payload = $this->makeUserPayload([
            'email' => $user->email,
        ]);

        $response = $this->post('/api/v1/users', $payload, $this->authHeaders());

        $response->assertStatus(400);
        $response->assertJsonPath('code', 400);
    }

    // ========== 更新接口测试 ==========

    public function test_update_user_partial_fields(): void
    {
        $user = $this->createUser();
        $suffix = bin2hex(random_bytes(4));
        $updated_email = 'updated_' . $suffix . '@example.com';
        $ext = ['nickname' => 'Tester'];

        $response = $this->put('/api/v1/users/' . $user->id, [
            'email' => $updated_email,
            'ext' => $ext,
        ], $this->authHeaders());

        $response->assertStatus(200);
        $response->assertJsonPath('code', 0);
        $response->assertJsonPath('data.email', $updated_email);
        $response->assertJsonPath('data.ext.nickname', 'Tester');

        $user->refresh();
        $this->assertSame($updated_email, $user->email);
        $this->assertSame($ext, $user->ext);
    }

    public function test_update_user_unique_conflict_returns_400(): void
    {
        $existing = $this->createUser();
        $target = $this->createUser();

        $response = $this->put('/api/v1/users/' . $target->id, [
            'username' => $existing->username,
        ], $this->authHeaders());

        $response->assertStatus(400);
        $response->assertJsonPath('code', 400);
    }

    public function test_update_user_not_found_returns_404(): void
    {
        $response = $this->put('/api/v1/users/999999', [
            'email' => 'missing@example.com',
        ], $this->authHeaders());

        $response->assertStatus(404);
        $response->assertJsonPath('code', 404);
    }

    // ========== 状态切换接口测试 ==========

    public function test_patch_user_status_updates_status(): void
    {
        $user = $this->createUser();

        $response = $this->patch('/api/v1/users/' . $user->id . '/status', [
            'status' => 0,
        ], $this->authHeaders());

        $response->assertStatus(200);
        $response->assertJsonPath('code', 0);
        $response->assertJsonPath('data.status', 0);

        $user->refresh();
        $this->assertSame(0, $user->status);
    }

    public function test_patch_user_status_invalid_returns_400(): void
    {
        $user = $this->createUser();

        $response = $this->patch('/api/v1/users/' . $user->id . '/status', [
            'status' => 2,
        ], $this->authHeaders());

        $response->assertStatus(400);
        $response->assertJsonPath('code', 400);
    }

    public function test_patch_user_status_not_found_returns_404(): void
    {
        $response = $this->patch('/api/v1/users/999999/status', [
            'status' => 0,
        ], $this->authHeaders());

        $response->assertStatus(404);
        $response->assertJsonPath('code', 404);
    }

    // ========== 认证拦截测试 ==========

    public function test_list_users_without_token_returns_401(): void
    {
        $response = $this->get('/api/v1/users');

        $response->assertStatus(401);
    }

    public function test_show_user_without_token_returns_401(): void
    {
        $response = $this->get('/api/v1/users/1');

        $response->assertStatus(401);
    }
}
