<?php

namespace Tests\Feature;

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

class AdminPlatformOrderIndexSummaryGovernanceLinksShouldHaveDataRoleAndKeepBackTest 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_summary_governance_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-summary-link-bmpa-success-orders',
                'expect' => ['bmpa_success_only' => '1'],
                'must_not_have' => ['page'],
            ],
            [
                'role' => 'po-summary-link-bmpa-failed-orders',
                'expect' => ['bmpa_failed_only' => '1'],
                'must_not_have' => ['page', 'fail_only'],
            ],
            [
                'role' => 'po-summary-link-syncable-orders',
                'expect' => ['syncable_only' => '1', 'sync_status' => 'unsynced'],
                'must_not_have' => ['page', 'fail_only'],
            ],
            [
                'role' => 'po-summary-link-renewal-missing-sub-orders',
                'expect' => ['renewal_missing_subscription' => '1'],
                'must_not_have' => ['page'],
            ],
        ];

        foreach ($cases as $c) {
            $role = (string) ($c['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);
            }

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

            foreach (($c['must_not_have'] ?? []) as $key) {
                $this->assertArrayNotHasKey((string) $key, $q, $role . ' should clear ' . $key);
            }
        }
    }
}
