/**
 * Shared helpers for clients/{clientId}/security/blockedIps (Firebase RTDB keys + lookup).
 */

export const DEFAULT_BLOCKED_VISITOR_MESSAGE = 'You are blocked for unusual behaviour.';

/** RTDB-safe key for an IP (dots/colons → underscores). */
export function ipToBlockedIpFirebaseKey(ip) {
    const s = String(ip || '').trim();
    if (!s) return '';
    if (s.includes('.')) return s.replace(/\./g, '_');
    if (s.includes(':')) return s.replace(/:/g, '_');
    return `raw_${s.replace(/[.#$\[\]\/]/g, '_')}`;
}

/** True if currentIp matches any entry in blockedMap (by key or stored .ip field). */
export function isIpInBlockedMap(currentIp, blockedMap) {
    if (!currentIp || !blockedMap || typeof blockedMap !== 'object') return false;
    const key = ipToBlockedIpFirebaseKey(currentIp);
    if (key && blockedMap[key] != null) return true;
    for (const v of Object.values(blockedMap)) {
        if (v && typeof v === 'object' && String(v.ip || '').trim() === currentIp) return true;
        if (typeof v === 'string' && v.trim() === currentIp) return true;
    }
    return false;
}

/** Loose IPv4 check for manual entry in dashboard. */
export function looksLikeIpv4(ip) {
    const s = String(ip || '').trim();
    if (!/^\d{1,3}(\.\d{1,3}){3}$/.test(s)) return false;
    return s.split('.').every((n) => {
        const x = Number(n);
        return x >= 0 && x <= 255;
    });
}
