<?php
declare(strict_types=1);

namespace App\Seo;

use App\Support\PublicPageType;

final class CanonicalPolicy
{
    /** @var array<string,string> */
    private const PAGE_KEYS = [
        'topics' => 'page',
        'question' => 'answers_page',
        'topic' => 'comments_page',
        'category' => 'page',
        'tag' => 'page',
    ];

    /** @param array<string,mixed> $query */
    public static function forPage(string $pageType, string $path, array $query): string
    {
        $pageType = PublicPageType::normalize($pageType);
        $parsedPath = parse_url($path, PHP_URL_PATH);
        $path = is_string($parsedPath) && $parsedPath !== '' ? $parsedPath : '/';
        $path = '/' . ltrim($path, '/');

        $key = self::PAGE_KEYS[$pageType] ?? null;
        if ($key === null) return $path;

        $page = filter_var($query[$key] ?? null, FILTER_VALIDATE_INT, ['options' => ['min_range' => 1]]);
        if ($page === false || $page === null || (int) $page <= 1) return $path;

        return $path . '?' . http_build_query([$key => (int) $page], '', '&', PHP_QUERY_RFC3986);
    }
}
