<?php

namespace Tests\Feature;

use Illuminate\Foundation\Testing\RefreshDatabase;
use Tests\TestCase;

class AdminPlatformOrderIndexSopLinksShouldHaveDataRoleAndKeepBackTest extends TestCase
{
    use RefreshDatabase;

    protected function loginAsPlatformAdmin(): void
    {
        $this->seed();

        $this->post('/admin/login', [
            'email' => 'platform.admin@demo.local',
            'password' => 'Platform@123456',
        ])->assertRedirect('/admin');
    }

    public function test_platform_orders_index_sop_links_should_have_data_role_and_keep_back(): void
    {
        $this->loginAsPlatformAdmin();

        $res = $this->get('/admin/platform-orders?merchant_id=1&back=/admin&page=2');
        $res->assertOk();

        $html = (string) $res->getContent();

        $cases = [
            [
                'role' => 'po-sop-link-reconcile-mismatch',
                'expect' => ['reconcile_mismatch' => '1'],
            ],
            [
                'role' => 'po-sop-link-refund-inconsistent',
                'expect' => ['refund_inconsistent' => '1'],
            ],
            [
                'role' => 'po-sop-link-syncable',
                'expect' => ['syncable_only' => '1', 'sync_status' => 'unsynced'],
            ],
        ];

        foreach ($cases as $c) {
            $role = (string) ($c['role'] ?? '');
            $this->assertNotSame('', $role);

            $re = '/<a[^>]*data-role="' . preg_quote($role, '/') . '"[^>]*href="([^"]+)"/u';
            $this->assertMatchesRegularExpression($re, $html);
            preg_match($re, $html, $m);

            $rawHref = (string) ($m[1] ?? '');
            $this->assertStringNotContainsString('&amp;back=', $rawHref);

            $href = html_entity_decode($rawHref);
            $query = parse_url($href, PHP_URL_QUERY) ?: '';
            parse_str($query, $q);

            foreach (($c['expect'] ?? []) as $k => $v) {
                $this->assertSame((string) $v, (string) ($q[$k] ?? ''), $role . ' missing expected ' . $k);
            }

            // SOP 链接应保留 back，并清空 page
            $this->assertSame('/admin', (string) ($q['back'] ?? ''));
            $this->assertArrayNotHasKey('page', $q);
        }
    }
}
