<?php

declare(strict_types=1);

namespace HyperfTest\Cases\Integration\Order;

use App\Model\OrderItem;
use HyperfTest\TestCase;
use HyperfTest\Traits\AuthenticatedTestTrait;

/**
 * OrderItemController 集成测试
 *
 * 覆盖列表分页/筛选、详情含父订单、DataScope 过滤、401/404
 *
 * @internal
 * @coversNothing
 */
class OrderItemControllerTest extends TestCase
{
    use AuthenticatedTestTrait;

    protected function hasOrderItemData(): bool
    {
        return $this->runInCoroutine(static function (): bool {
            return OrderItem::query()->exists();
        });
    }

    protected function getFirstOrderItemId(): ?int
    {
        return $this->runInCoroutine(static function (): ?int {
            return OrderItem::query()->value('id');
        });
    }

    // ========== 列表接口 ==========

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

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

    public function test_list_respects_per_page(): void
    {
        $response = $this->get('/api/v1/order-items', ['per_page' => 5], $this->authHeaders());

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

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

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

    public function test_list_contains_expected_fields(): void
    {
        if (!$this->hasOrderItemData()) {
            $this->markTestSkipped('没有订单项数据');
        }

        $response = $this->get('/api/v1/order-items', [], $this->authHeaders());

        $response->assertStatus(200);
        $body = json_decode($response->getContent(), true);
        $first_item = $body['data']['items'][0];

        $expected_keys = [
            'id', 'company_id', 'platform_id', 'store_id', 'order_id',
            'platform_order_id', 'sub_order_id', 'platform_product_id',
            'product_sku', 'unit_price', 'quantity', 'discount', 'total',
            'created_date',
        ];

        foreach ($expected_keys as $key) {
            $this->assertArrayHasKey($key, $first_item, "列表缺少字段: {$key}");
        }
    }

    public function test_list_excludes_detail_only_fields(): void
    {
        if (!$this->hasOrderItemData()) {
            $this->markTestSkipped('没有订单项数据');
        }

        $response = $this->get('/api/v1/order-items', [], $this->authHeaders());

        $response->assertStatus(200);
        $body = json_decode($response->getContent(), true);
        $first_item = $body['data']['items'][0];

        // 列表不含仅详情字段
        $this->assertArrayNotHasKey('ext', $first_item);
        $this->assertArrayNotHasKey('product_barcode', $first_item);
        $this->assertArrayNotHasKey('sub_order_type_id', $first_item);
    }

    // ========== 列表筛选 ==========

    public function test_list_filter_by_company_id(): void
    {
        if (!$this->hasOrderItemData()) {
            $this->markTestSkipped('没有订单项数据');
        }

        $company_id = $this->runInCoroutine(static function (): mixed {
            return OrderItem::query()->value('company_id');
        });

        $response = $this->get('/api/v1/order-items', ['company_id' => $company_id], $this->authHeaders());

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

        foreach ($body['data']['items'] as $item) {
            $this->assertSame($company_id, $item['company_id']);
        }
    }

    public function test_list_filter_by_order_id(): void
    {
        if (!$this->hasOrderItemData()) {
            $this->markTestSkipped('没有订单项数据');
        }

        $order_id = $this->runInCoroutine(static function (): mixed {
            return OrderItem::query()->value('order_id');
        });

        $response = $this->get('/api/v1/order-items', ['order_id' => $order_id], $this->authHeaders());

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

        foreach ($body['data']['items'] as $item) {
            $this->assertSame($order_id, $item['order_id']);
        }
    }

    public function test_list_filter_by_platform_order_id(): void
    {
        if (!$this->hasOrderItemData()) {
            $this->markTestSkipped('没有订单项数据');
        }

        $platform_order_id = $this->runInCoroutine(static function (): mixed {
            return OrderItem::query()->value('platform_order_id');
        });

        $response = $this->get('/api/v1/order-items', ['platform_order_id' => $platform_order_id], $this->authHeaders());

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

        foreach ($body['data']['items'] as $item) {
            $this->assertSame($platform_order_id, $item['platform_order_id']);
        }
    }

    public function test_list_filter_by_platform_product_id(): void
    {
        if (!$this->hasOrderItemData()) {
            $this->markTestSkipped('没有订单项数据');
        }

        $platform_product_id = $this->runInCoroutine(static function (): mixed {
            return OrderItem::query()->value('platform_product_id');
        });

        $response = $this->get('/api/v1/order-items', ['platform_product_id' => $platform_product_id], $this->authHeaders());

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

        foreach ($body['data']['items'] as $item) {
            $this->assertSame($platform_product_id, $item['platform_product_id']);
        }
    }

    public function test_list_filter_by_product_sku(): void
    {
        if (!$this->hasOrderItemData()) {
            $this->markTestSkipped('没有订单项数据');
        }

        $product_sku = $this->runInCoroutine(static function (): mixed {
            return OrderItem::query()->whereNotNull('product_sku')->where('product_sku', '!=', '')->value('product_sku');
        });

        if (!$product_sku) {
            $this->markTestSkipped('没有有 SKU 的订单项数据');
        }

        $response = $this->get('/api/v1/order-items', ['product_sku' => $product_sku], $this->authHeaders());

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

        foreach ($body['data']['items'] as $item) {
            $this->assertSame($product_sku, $item['product_sku']);
        }
    }

    public function test_list_filter_by_created_date_range(): void
    {
        if (!$this->hasOrderItemData()) {
            $this->markTestSkipped('没有订单项数据');
        }

        $response = $this->get('/api/v1/order-items', [
            'created_date_from' => '2020-01-01',
            'created_date_to' => '2099-12-31',
        ], $this->authHeaders());

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

        $this->assertGreaterThanOrEqual(0, $body['data']['total']);
    }

    // ========== 详情接口 ==========

    public function test_detail_returns_order_item(): void
    {
        $id = $this->getFirstOrderItemId();
        if (!$id) {
            $this->markTestSkipped('没有订单项数据');
        }

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

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

    public function test_detail_contains_parent_order(): void
    {
        $id = $this->getFirstOrderItemId();
        if (!$id) {
            $this->markTestSkipped('没有订单项数据');
        }

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

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

        $this->assertArrayHasKey('parent_order', $body['data'], '订单项详情应包含 parent_order');
    }

    public function test_detail_parent_order_has_expected_fields(): void
    {
        $id = $this->getFirstOrderItemId();
        if (!$id) {
            $this->markTestSkipped('没有订单项数据');
        }

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

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

        $parent_order = $body['data']['parent_order'];
        if ($parent_order === null) {
            $this->markTestSkipped('该订单项无关联父订单');
        }

        $expected_keys = ['id', 'platform_order_id', 'order_status_id', 'total_amount', 'total_paid', 'created_date', 'paid_date'];
        foreach ($expected_keys as $key) {
            $this->assertArrayHasKey($key, $parent_order, "父订单摘要缺少字段: {$key}");
        }
    }

    public function test_detail_contains_ext(): void
    {
        $id = $this->getFirstOrderItemId();
        if (!$id) {
            $this->markTestSkipped('没有订单项数据');
        }

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

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

        $this->assertArrayHasKey('ext', $body['data']);
    }

    public function test_detail_contains_full_fields(): void
    {
        $id = $this->getFirstOrderItemId();
        if (!$id) {
            $this->markTestSkipped('没有订单项数据');
        }

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

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

        // 详情应包含完整字段（列表中不含的额外字段）
        $this->assertArrayHasKey('product_barcode', $body['data']);
        $this->assertArrayHasKey('sub_order_type_id', $body['data']);
        $this->assertArrayHasKey('created_at', $body['data']);
        $this->assertArrayHasKey('updated_at', $body['data']);
    }

    public function test_detail_not_found_returns_404(): void
    {
        $response = $this->get('/api/v1/order-items/999999999', [], $this->authHeaders());

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

    // ========== 认证拦截 ==========

    public function test_list_without_token_returns_401(): void
    {
        $response = $this->get('/api/v1/order-items');

        $response->assertStatus(401);
    }

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

        $response->assertStatus(401);
    }
}
