<?php declare(strict_types = 1);

namespace idoit\Module\SyneticsFlows\Controller;

use idoit\Module\SyneticsFlows\Serialization\Serializer;
use Throwable;

class SearchParams
{
    public function __construct(
        private int $page = 0,
        private int $perPage = 100,
        private ?Sort $sort = null,
    )
    {
    }

    public function getPage(): int
    {
        return $this->page;
    }

    public function getOffset(): int
    {
        return max(0, $this->page - 1) * $this->perPage;
    }

    public function getPerPage(): int
    {
        return $this->perPage;
    }

    public function getSort(): ?Sort
    {
        return $this->sort;
    }

    public static function fromParams(?string $params): SearchParams
    {
        $result = new SearchParams();
        try {
            $result = Serializer::fromJson(SearchParams::class, json_decode($params, true));
        } catch (Throwable) {
            // fallback
        }
        return $result;
    }
}