<?php

declare(strict_types=1);

/**
 * 探索列表（index.php）網址查詢參數；勿帶 store.php 的 id。
 *
 * @param array<string, mixed> $sourceGet 通常為 $_GET
 * @param array<string, mixed> $overrides
 */
function fate_build_home_list_query(array $sourceGet, array $overrides = []): string
{
    $allowed = ['city', 'sort', 'q', 'page', 'listing'];
    $merged = [];
    foreach ($allowed as $key) {
        if (array_key_exists($key, $overrides)) {
            $v = $overrides[$key];
            if ($v !== null && $v !== '') {
                $merged[$key] = (string) $v;
            }
            continue;
        }
        if (!isset($sourceGet[$key])) {
            continue;
        }
        $v = $sourceGet[$key];
        if ($v === null || $v === '') {
            continue;
        }
        $merged[$key] = (string) $v;
    }

    $qs = http_build_query($merged, '', '&', PHP_QUERY_RFC3986);

    return 'index.php' . ($qs !== '' ? '?' . $qs : '');
}
