<?php

namespace Tests\Feature;

use App\Support\BackUrl;
use PHPUnit\Framework\Attributes\DataProvider;
use Tests\TestCase;

class BackUrlSanitizeForLinksShouldRejectUnsafeBackTest extends TestCase
{
    public static function unsafeBackProvider(): array
    {
        return [
            'empty' => ['', ''],
            'no_slash_prefix' => ['admin', ''],
            'protocol_relative' => ['//evil.com/x', ''],
            'absolute_url' => ['https://evil.com/x', ''],
            'quote_injection' => ['/admin?x=" onclick="alert(1)', ''],
            'angle_injection' => ['/admin?<script>', ''],
            'crlf_plain' => ["/admin\nSet-Cookie: x=1", ''],
            'crlf_encoded' => ['/admin?x=%0aSet-Cookie%3A1', ''],
            'nested_back_query' => ['/admin?back=/admin', ''],
            'nested_back_encoded' => ['/admin?x=1%26back%3D%2Fadmin', ''],
            'nested_back_double_encoded' => ['/admin?x=1%2526back%253D%252Fadmin', ''],
            'too_long' => ['/' . str_repeat('a', 2100), ''],
        ];
    }

    public static function safeBackProvider(): array
    {
        return [
            'simple' => ['/admin', '/admin'],
            'with_query' => ['/admin/platform-orders?sync_status=failed', '/admin/platform-orders?sync_status=failed'],
            'with_fragment' => ['/admin/platform-orders#payment-receipts', '/admin/platform-orders#payment-receipts'],
        ];
    }

    #[DataProvider('unsafeBackProvider')]
    public function test_sanitize_for_links_should_reject_unsafe_back(string $incoming, string $expected): void
    {
        $this->assertSame($expected, BackUrl::sanitizeForLinks($incoming));
    }

    #[DataProvider('safeBackProvider')]
    public function test_sanitize_for_links_should_keep_safe_back(string $incoming, string $expected): void
    {
        $this->assertSame($expected, BackUrl::sanitizeForLinks($incoming));
    }
}
