<?php

readonly class CF_ContainerListArguments
{
    public const DEFAULT_SORT_COLUMN = 'started_at';
    public const DEFAULT_SORT_DIRECTION = 'desc';
    public const DEFAULT_PER_PAGE = 20;
    public const DEFAULT_PAGE = 1;

    public function __construct(
        public int $per_page = self::DEFAULT_PER_PAGE,
        public int $page = self::DEFAULT_PAGE,
        public string $sort = self::DEFAULT_SORT_COLUMN,
        public string $order = self::DEFAULT_SORT_DIRECTION,
        public ?string $hostkey = null,
        public ?string $owner = null,
        public ?string $name = null,
        public ?string $image = null,
        public ?string $state = null,
        public ?string $engine = null,
        public ?array $container_port = null,
    ) {}

    public static function fromArray(array $data): self
    {
        $containerPort = $data['container_port'] ?? null;
        if ($containerPort !== null && !is_array($containerPort)) {
            $containerPort = [$containerPort];
        }
        if (is_array($containerPort)) {
            $containerPort = array_values(array_filter(array_map('intval', $containerPort), fn($v) => $v > 0));
            if (empty($containerPort)) {
                $containerPort = null;
            }
        }

        return new self(
            $data['per_page'] ?? self::DEFAULT_PER_PAGE,
            $data['page'] ?? self::DEFAULT_PAGE,
            $data['sort'] ?? self::DEFAULT_SORT_COLUMN,
            $data['order'] ?? self::DEFAULT_SORT_DIRECTION,
            $data['hostkey'] ?? null,
            $data['owner'] ?? null,
            $data['name'] ?? null,
            $data['image'] ?? null,
            $data['state'] ?? null,
            $data['engine'] ?? null,
            $containerPort,
        );
    }

    public function toGetParameters(): string
    {
        $params = array_filter(
            [
                'page' => $this->page,
                'per_page' => $this->per_page,
                'sort' => $this->sort,
                'order' => $this->order,
                'hostkey' => $this->hostkey,
                'owner' => $this->owner,
                'name' => $this->name,
                'image' => $this->image,
                'state' => $this->state,
                'engine' => $this->engine,
                'container_port' => $this->container_port,
            ],
            fn($value) => $value !== null,
        );

        return http_build_query($params);
    }
}
