<?php

namespace Tests\Unit\AdOps;

use App\Services\AdOps\ListsService;
use PHPUnit\Framework\TestCase;

/**
 * ListsService has two public static helpers that run without the API client
 * or DB. They're the single ingestion path for user-supplied domains/keywords,
 * so regressions in either corrupt list contents silently.
 */
final class ListsServiceStaticsTest extends TestCase
{
    // ───────────────── parseDomainsBlob

    public function testParseDomainsBlobStripsProtocolAndPath(): void
    {
        $blob = "https://example.com/path?q=1\nhttp://Foo.Bar.io\nwww.baz.org";
        $domains = ListsService::parseDomainsBlob($blob);

        // Lowercased, protocol-stripped. The legacy regex extracts the first
        // domain match, which for "www.baz.org" is the full string.
        $this->assertContains('example.com', $domains);
        $this->assertContains('foo.bar.io', $domains);
        $this->assertContains('www.baz.org', $domains);
    }

    public function testParseDomainsBlobDeduplicates(): void
    {
        $blob = "example.com\nexample.com\nhttps://example.com/a\nhttps://example.com/b";
        $domains = ListsService::parseDomainsBlob($blob);

        $this->assertSame(1, count(array_filter($domains, fn($d) => $d === 'example.com')));
    }

    public function testParseDomainsBlobRejectsNonDomainStrings(): void
    {
        $blob = "notadomain\nlocalhost\n@@@\n12345";
        $domains = ListsService::parseDomainsBlob($blob);

        $this->assertSame([], $domains);
    }

    public function testParseDomainsBlobHandlesMixedLineEndings(): void
    {
        // CR/LF mix (Windows + Mac) must not create empty entries.
        $blob = "a.com\r\nb.com\rc.com\n";
        $domains = ListsService::parseDomainsBlob($blob);

        $this->assertContains('a.com', $domains);
        $this->assertContains('b.com', $domains);
        $this->assertContains('c.com', $domains);
        $this->assertCount(3, $domains);
    }

    // ───────────────── clearKeyword

    public function testClearKeywordStripsHttpAndLowercases(): void
    {
        $this->assertSame('example.com', ListsService::clearKeyword('HTTP://Example.com'));
        $this->assertSame('example.com', ListsService::clearKeyword('https://Example.com'));
    }

    public function testClearKeywordTrimsWhitespace(): void
    {
        $this->assertSame('buy shoes', ListsService::clearKeyword("   Buy Shoes\t\n"));
    }

    public function testClearKeywordLeavesPlainTextAlone(): void
    {
        $this->assertSame('running sneakers', ListsService::clearKeyword('Running Sneakers'));
    }

    public function testClearKeywordHandlesEmptyAndNull(): void
    {
        $this->assertSame('', ListsService::clearKeyword(''));
        $this->assertSame('', ListsService::clearKeyword(null));
    }
}
