import { Router, Request, Response } from 'express';

const router = Router();

// Simple in-memory cache: IP → { country_code, country_name, ts }
const geoCache = new Map<string, { country_code: string; country_name: string; ts: number }>();
const CACHE_TTL_MS = 10 * 60 * 1000; // 10 minutes

function getClientIp(req: Request): string {
  // Trust X-Forwarded-For from Apache reverse proxy
  const forwarded = req.headers['x-forwarded-for'];
  if (forwarded) {
    const first = (typeof forwarded === 'string' ? forwarded : forwarded[0]).split(',')[0].trim();
    if (first) return first;
  }
  const realIp = req.headers['x-real-ip'];
  if (realIp) return typeof realIp === 'string' ? realIp : realIp[0];
  return req.socket.remoteAddress || '127.0.0.1';
}

// GET /api/geo/country
router.get('/country', async (req: Request, res: Response) => {
  try {
    const ip = getClientIp(req);

    // Check cache
    const cached = geoCache.get(ip);
    if (cached && Date.now() - cached.ts < CACHE_TTL_MS) {
      res.json({
        country_code: cached.country_code,
        country_name: cached.country_name,
        source: 'ip',
      });
      return;
    }

    // Call ipwho.is (free, HTTPS, 10k req/month)
    const controller = new AbortController();
    const timeout = setTimeout(() => controller.abort(), 3000);

    const apiRes = await fetch(`https://ipwho.is/${ip}?fields=country_code,country`, {
      signal: controller.signal,
    });
    clearTimeout(timeout);

    const data = await apiRes.json() as { success?: boolean; country_code?: string; country?: string };

    if (data.country_code) {
      const result = { country_code: data.country_code, country_name: data.country || '' };
      geoCache.set(ip, { ...result, ts: Date.now() });

      // Evict stale entries periodically
      if (geoCache.size > 5000) {
        const cutoff = Date.now() - CACHE_TTL_MS;
        for (const [k, v] of geoCache) {
          if (v.ts < cutoff) geoCache.delete(k);
        }
      }

      res.json({ ...result, source: 'ip' });
      return;
    }

    // Fallback if lookup fails
    res.json({ country_code: '', country_name: '', source: 'unknown' });
  } catch (err) {
    // Don't fail the signup flow over geo detection
    res.json({ country_code: '', country_name: '', source: 'unknown' });
  }
});

export default router;
