<?php

namespace Tests\Feature;

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

class AdminDashboardBillingWorkbenchButtonsShouldIncludeBackQueryTest 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_dashboard_billing_workbench_buttons_should_include_back_query(): void
    {
        $this->loginAsPlatformAdmin();

        $res = $this->get('/admin');
        $res->assertOk();

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

        $roles = [
            'dashboard-po-quicklink-bmpa-processable',
            'dashboard-po-quicklink-syncable',
            'dashboard-po-quicklink-sync-failed',
            'dashboard-po-quicklink-paid-no-receipt',
            'dashboard-po-quicklink-reconcile-mismatch',
            'dashboard-po-quicklink-refund-inconsistent',
        ];

        foreach ($roles as $role) {
            $this->assertMatchesRegularExpression('/<a[^>]*data-role="' . preg_quote($role, '/') . '"[^>]*href="([^"]+)"/u', $html);
            preg_match('/<a[^>]*data-role="' . preg_quote($role, '/') . '"[^>]*href="([^"]+)"/u', $html, $m);
            $href = html_entity_decode($m[1] ?? '');
            $query = parse_url($href, PHP_URL_QUERY) ?: '';
            parse_str($query, $q);

            $this->assertSame('/admin', (string) ($q['back'] ?? ''));
        }

        // 避免 Blade 把 URL escape 成 &amp;back=（会导致 back 被错误编码/叠加）
        $res->assertDontSee('&amp;back=', false);
    }
}
