import fs from 'node:fs';
import path from 'node:path';

function normalizeChatId(value) {
  if (!value) return null;
  const raw = String(value).trim();
  if (!raw) return null;
  if (raw.includes('@')) return raw;
  const digits = raw.replace(/[^0-9]/g, '');
  if (!digits) return null;
  return `${digits}@s.whatsapp.net`;
}

export function loadAllowlist(filePath) {
  if (!filePath) return new Set();
  try {
    const text = fs.readFileSync(filePath, 'utf8');
    const entries = text
      .split(/\r?\n/)
      .map(line => line.split('#')[0].trim())
      .filter(Boolean)
      .map(normalizeChatId)
      .filter(Boolean);
    return new Set(entries);
  } catch (err) {
    if (err.code !== 'ENOENT') throw err;
    return new Set();
  }
}

export function watchAllowlist(filePath, onChange) {
  if (!filePath) return () => {};
  const dir = path.dirname(filePath);
  try {
    fs.mkdirSync(dir, { recursive: true });
  } catch {}
  let timer = null;
  const reload = () => {
    clearTimeout(timer);
    timer = setTimeout(() => {
      try {
        onChange(loadAllowlist(filePath));
      } catch (err) {
        console.error('[whatsapp-bridge] allowlist reload failed:', err.message);
      }
    }, 200);
  };
  try {
    const watcher = fs.watch(dir, (_event, name) => {
      if (name === path.basename(filePath)) reload();
    });
    return () => {
      clearTimeout(timer);
      watcher.close();
    };
  } catch (err) {
    console.error('[whatsapp-bridge] allowlist watch failed:', err.message);
    return () => {};
  }
}

export function isAllowed(allowSet, chatId) {
  if (!allowSet || allowSet.size === 0) return false;
  const normalized = normalizeChatId(chatId);
  if (!normalized) return false;
  return allowSet.has(normalized);
}

export { normalizeChatId };
