<?php

declare(strict_types=1);

namespace App\Tests\Integration\Admin;

use App\Domain\Auth\Role;
use App\Domain\Auth\TokenKind;
use App\Domain\Ip\IpAddress;
use App\Tests\Integration\Support\AppTestCase;

/**
 * `/admin/ips/countries` — distinct ISO codes from `ip_enrichment` with
 * counts. Empty when there's nothing to show; sorted by code.
 */
final class CountriesEndpointTest extends AppTestCase
{
    public function testReturnsEmptyWhenNothingEnriched(): void
    {
        $token = $this->createToken(TokenKind::Admin, Role::Viewer);
        $resp = $this->request('GET', '/api/v1/admin/ips/countries', [
            'Authorization' => 'Bearer ' . $token,
        ]);
        self::assertSame(200, $resp->getStatusCode());
        $body = $this->decode($resp);
        self::assertSame([], $body['items']);
    }

    public function testReturnsCountriesWithCounts(): void
    {
        $now = (new \DateTimeImmutable('now', new \DateTimeZone('UTC')))->format('Y-m-d H:i:s');
        foreach ([['1.1.1.1', 'GB'], ['2.2.2.2', 'GB'], ['3.3.3.3', 'US']] as [$ip, $cc]) {
            $bin = IpAddress::fromString($ip)->binary();
            $this->db->insert('ip_enrichment', [
                'ip_bin' => $bin,
                'country_code' => $cc,
                'asn' => null,
                'as_org' => null,
                'enriched_at' => $now,
            ], ['ip_bin' => \Doctrine\DBAL\ParameterType::LARGE_OBJECT]);
        }

        $token = $this->createToken(TokenKind::Admin, Role::Viewer);
        $resp = $this->request('GET', '/api/v1/admin/ips/countries', [
            'Authorization' => 'Bearer ' . $token,
        ]);
        self::assertSame(200, $resp->getStatusCode());
        $body = $this->decode($resp);
        self::assertSame([
            ['code' => 'GB', 'count' => 2],
            ['code' => 'US', 'count' => 1],
        ], $body['items']);
    }

    public function testRequiresViewer(): void
    {
        $resp = $this->request('GET', '/api/v1/admin/ips/countries');
        self::assertSame(401, $resp->getStatusCode());
    }
}
