<?php

declare(strict_types=1);

namespace App\ApiClient\DTOs;

/**
 * One row in the admin IP search response. Mirrors the api shape from
 * SPEC §M09.1.
 */
final class IpListItem
{
    /**
     * @param array{country_code: ?string, asn: ?int, as_org: ?string, enriched_at: ?string}|null $enrichment
     */
    public function __construct(
        public readonly string $ip,
        public readonly bool $isIpv4,
        public readonly float $maxScore,
        public readonly ?string $topCategory,
        public readonly int $pairCount,
        public readonly ?string $lastReportAt,
        public readonly string $status,
        public readonly ?array $enrichment,
    ) {
    }

    /**
     * @param array<string, mixed> $row
     */
    public static function fromArray(array $row): self
    {
        $enrichment = null;
        if (isset($row['enrichment']) && is_array($row['enrichment'])) {
            $enrichment = [
                'country_code' => isset($row['enrichment']['country_code']) ? (string) $row['enrichment']['country_code'] : null,
                'asn' => isset($row['enrichment']['asn']) && $row['enrichment']['asn'] !== null ? (int) $row['enrichment']['asn'] : null,
                'as_org' => isset($row['enrichment']['as_org']) ? (string) $row['enrichment']['as_org'] : null,
                'enriched_at' => isset($row['enrichment']['enriched_at']) ? (string) $row['enrichment']['enriched_at'] : null,
            ];
        }

        return new self(
            ip: (string) ($row['ip'] ?? ''),
            isIpv4: (bool) ($row['is_ipv4'] ?? false),
            maxScore: (float) ($row['max_score'] ?? 0),
            topCategory: isset($row['top_category']) && $row['top_category'] !== null ? (string) $row['top_category'] : null,
            pairCount: (int) ($row['pair_count'] ?? 0),
            lastReportAt: isset($row['last_report_at']) && $row['last_report_at'] !== null ? (string) $row['last_report_at'] : null,
            status: (string) ($row['status'] ?? 'clean'),
            enrichment: $enrichment,
        );
    }
}
