<?php

declare(strict_types=1);

namespace HyperfTest\Cases\Integration\Sku;

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

/**
 * SkuOriginController 集成测试
 *
 * 覆盖列表分页、筛选、详情、创建校验、认证拦截
 *
 * @internal
 * @coversNothing
 */
class SkuOriginControllerTest extends TestCase
{
    use AuthenticatedTestTrait;

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

    protected function getFirstRecord(): ?array
    {
        return $this->runInCoroutine(static function (): ?array {
            $record = SkuOrigin::query()->first();
            return $record ? $record->toArray() : null;
        });
    }

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

    public function test_list_returns_paginated_data(): void
    {
        $response = $this->get('/api/v1/sku-origins', [], $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/sku-origins', ['per_page' => 5], $this->authHeaders());

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

    public function test_list_filter_by_company_id(): void
    {
        if (!$this->hasData()) {
            $this->markTestSkipped('没有 SKU Origin 数据');
        }

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

        $response = $this->get('/api/v1/sku-origins', ['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_sku(): void
    {
        if (!$this->hasData()) {
            $this->markTestSkipped('没有 SKU Origin 数据');
        }

        $first = $this->getFirstRecord();
        $sku_fragment = substr($first['sku'], 0, 3);

        $response = $this->get('/api/v1/sku-origins', ['sku' => $sku_fragment], $this->authHeaders());

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

        foreach ($body['data']['items'] as $item) {
            $this->assertStringContainsStringIgnoringCase($sku_fragment, $item['sku']);
        }
    }

    public function test_list_filter_by_barcode(): void
    {
        if (!$this->hasData()) {
            $this->markTestSkipped('没有 SKU Origin 数据');
        }

        $first = $this->getFirstRecord();
        if (empty($first['barcode'])) {
            $this->markTestSkipped('首条记录无 barcode');
        }

        $barcode_fragment = substr($first['barcode'], 0, 4);
        $response = $this->get('/api/v1/sku-origins', ['barcode' => $barcode_fragment], $this->authHeaders());

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

        foreach ($body['data']['items'] as $item) {
            $this->assertStringContainsStringIgnoringCase($barcode_fragment, $item['barcode']);
        }
    }

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

    public function test_detail_returns_sku_origin(): void
    {
        $first = $this->getFirstRecord();
        if (!$first) {
            $this->markTestSkipped('没有 SKU Origin 数据');
        }

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

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

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

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

    // ========== 创建校验 ==========

    public function test_create_requires_barcode(): void
    {
        $response = $this->post('/api/v1/sku-origins', [
            'company_id' => 1,
            'sku' => 'TEST-NO-BARCODE-' . uniqid(),
            'name' => 'Test Product',
        ], $this->authHeaders());

        $response->assertStatus(422);
    }

    public function test_create_requires_sku(): void
    {
        $response = $this->post('/api/v1/sku-origins', [
            'company_id' => 1,
            'barcode' => '6901234567890',
            'name' => 'Test Product',
        ], $this->authHeaders());

        $response->assertStatus(422);
    }

    public function test_create_duplicate_company_sku_returns_422(): void
    {
        $first = $this->getFirstRecord();
        if (!$first) {
            $this->markTestSkipped('没有 SKU Origin 数据');
        }

        $response = $this->post('/api/v1/sku-origins', [
            'company_id' => $first['company_id'],
            'sku' => $first['sku'],
            'barcode' => '0000000000000',
            'name' => 'Duplicate Test',
        ], $this->authHeaders());

        $response->assertStatus(422);
    }

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

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

        $response->assertStatus(401);
    }
}
