<?php

declare(strict_types=1);

namespace App\ApiClient\DTOs;

/**
 * Page of IP search results with pagination metadata.
 */
final class IpListDto
{
    /**
     * @param list<IpListItem> $items
     */
    public function __construct(
        public readonly array $items,
        public readonly int $page,
        public readonly int $pageSize,
        public readonly int $total,
    ) {
    }

    /**
     * @param array<string, mixed> $payload
     */
    public static function fromArray(array $payload): self
    {
        $items = [];
        if (isset($payload['items']) && is_array($payload['items'])) {
            foreach ($payload['items'] as $row) {
                if (is_array($row)) {
                    $items[] = IpListItem::fromArray($row);
                }
            }
        }

        return new self(
            items: $items,
            page: (int) ($payload['page'] ?? 1),
            pageSize: (int) ($payload['page_size'] ?? 25),
            total: (int) ($payload['total'] ?? 0),
        );
    }

    public function totalPages(): int
    {
        if ($this->pageSize <= 0) {
            return 1;
        }

        return max(1, (int) ceil($this->total / $this->pageSize));
    }
}
