/*
|--------------------------------------------------------------------------
| Agência PSI
|--------------------------------------------------------------------------
| Criado e desenvolvido por Leonardo Nohama
|
| Tecnologia aplicada à escuta.
| Estrutura para o cuidado.
|
| Arquivo: src/utils/upgradeContext.js
| Data: 2026
| Local: São Carlos/SP — Brasil
|--------------------------------------------------------------------------
| © 2026 — Todos os direitos reservados
|--------------------------------------------------------------------------
*/

/**
 * Parse "missing" query param into array of unique feature keys.
 * Accepts:
 * - "feature_a"
 * - "feature_a,feature_b"
 * - ["feature_a", "feature_b"] (vue-router pode entregar array)
 */
export function parseMissingKeys(missing) {
    if (!missing) return [];

    const raw = Array.isArray(missing) ? missing.join(',') : String(missing);
    const keys = raw
        .split(',')
        .map((s) => s.trim())
        .filter(Boolean);

    // unique preserving order
    const seen = new Set();
    const unique = [];
    for (const k of keys) {
        if (!seen.has(k)) {
            seen.add(k);
            unique.push(k);
        }
    }
    return unique;
}

/**
 * Parse redirect param. Only allow internal app paths to avoid open-redirect.
 * - Must start with "/"
 * - Must NOT start with "//"
 */
export function parseRedirectTo(redirect) {
    if (!redirect) return null;
    const s = Array.isArray(redirect) ? redirect[0] : String(redirect);
    const trimmed = s.trim();
    if (!trimmed) return null;
    if (!trimmed.startsWith('/')) return null;
    if (trimmed.startsWith('//')) return null;
    return trimmed;
}

/**
 * Build /upgrade URL with missing feature and redirect target.
 */
export function buildUpgradeUrl({ missingKeys = [], redirectTo = null } = {}) {
    const keys = Array.isArray(missingKeys) ? missingKeys.filter(Boolean) : [];
    const q = new URLSearchParams();

    if (keys.length) q.set('missing', keys.join(','));
    if (redirectTo) q.set('redirect', redirectTo);

    const qs = q.toString();
    return qs ? `/upgrade?${qs}` : '/upgrade';
}
