<?php

declare(strict_types=1);

namespace HyperfTest\Cases\Integration\System;

use HyperfTest\TestCase;
use HyperfTest\Traits\AuthenticatedTestTrait;

/**
 * MqStatusController 集成测试
 *
 * 覆盖接口结构、队列参数筛选、无效参数 400、未认证 401
 *
 * @internal
 * @coversNothing
 */
class MqStatusControllerTest extends TestCase
{
    use AuthenticatedTestTrait;

    // ========== 正常返回结构 ==========

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

        // RabbitMQ 可能不可用，接受 200 或 500
        $status = $response->getStatusCode();
        if ($status === 500) {
            // 连接不可用时返回 500，仍验证响应格式
            $response->assertJsonStructure(['code', 'message', 'data']);
            $this->assertSame(500, $response->json('code'));
            $this->markTestSkipped('RabbitMQ not available');
        }

        $response->assertStatus(200);
        $response->assertJsonPath('code', 0);
        $response->assertJsonPath('message', '获取成功');
        $response->assertJsonStructure([
            'code',
            'message',
            'data' => [
                'business_queues',
                'retry_queues',
                'error_queue',
                'summary' => [
                    'total_messages',
                    'total_consumers',
                ],
                'fetched_at',
            ],
        ]);
    }

    // ========== 队列类型筛选 ==========

    public function test_mq_status_with_valid_queue_filter(): void
    {
        $response = $this->get('/api/v1/mq/status', ['queue' => 'orders'], $this->authHeaders());

        $status = $response->getStatusCode();
        if ($status === 500) {
            $this->markTestSkipped('RabbitMQ not available');
        }

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

        $data = $response->json('data');

        // 筛选时 business_queues 仅包含 orders.queue
        foreach ($data['business_queues'] as $queue) {
            $this->assertStringContainsString('orders', $queue['queue']);
        }

        // 筛选时 error_queue 为空数组（仅全量查询时返回）
        $this->assertEmpty($data['error_queue']);
    }

    // ========== 无效参数 ==========

    public function test_mq_status_with_invalid_queue_returns_400(): void
    {
        $response = $this->get('/api/v1/mq/status', ['queue' => 'invalid_type'], $this->authHeaders());

        $response->assertStatus(400);
        $this->assertSame(400, $response->json('code'));
        $this->assertStringContainsString('无效的队列类型', $response->json('message'));
    }

    // ========== 认证检查 ==========

    public function test_mq_status_without_token_returns_401(): void
    {
        $response = $this->get('/api/v1/mq/status');

        $response->assertStatus(401);
    }
}
