<?php

readonly class CF_ContainerVolumeListArguments
{
    public const DEFAULT_SORT_COLUMN = 'created_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 $volume_name = null,
        public ?string $driver = null,
    ) {}

    public static function fromArray(array $data): self
    {
        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['volume_name'] ?? null,
            $data['driver'] ?? null,
        );
    }

    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,
                'volume_name' => $this->volume_name,
                'driver' => $this->driver,
            ],
            fn($value) => $value !== null,
        );

        return http_build_query($params);
    }
}
