import { getSiteConfig } from '@/config/site';

/**
 * Bot Filter — Config-driven, no rebuild needed.
 * Baca blockedBots & allowedBots dari site_config.json secara real-time.
 *
 * botBlockMode:
 *  - "404"      → return notFound() (default)
 *  - "empty"    → return halaman kosong 200
 */

export type BotCheckResult =
  | { blocked: false }
  | { blocked: true; mode: string };

export function checkBot(userAgent: string | null): BotCheckResult {
  if (!userAgent) return { blocked: false };

  const config = getSiteConfig();
  const ua = userAgent.toLowerCase();

  const blockedBots: string[] = Array.isArray(config.blockedBots) ? config.blockedBots : [];
  const allowedBots: string[] = Array.isArray(config.allowedBots) ? config.allowedBots : [];
  const mode: string = config.botBlockMode || '404';

  // Cek allowlist dulu — allowedBots selalu MENANG
  for (const allowed of allowedBots) {
    const term = allowed.toLowerCase();
    if (ua.includes(term)) {
      return { blocked: false };
    }
  }

  // Cek blocklist — hanya match jika nama bot ada sebagai token tersendiri
  // Menggunakan word-boundary untuk mencegah false positive (misal "Moz" → "Mozilla")
  for (const blocked of blockedBots) {
    const term = blocked.toLowerCase();
    // Bangun regex: cek kecocokan sebagai substring lengkap (diawali/diakhiri non-alfanumerik)
    const pattern = new RegExp(`(^|[^a-z0-9])${term.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}([^a-z0-9]|$)`, 'i');
    if (pattern.test(ua)) {
      return { blocked: true, mode };
    }
  }

  return { blocked: false };
}
