import { Router, type Request, type Response } from 'express';
import { fetchGeoContext } from '../lib/geoClient.js';
import { resolveLocale } from '../lib/resolveLocale.js';

const router = Router();

function getHeaders(req: Request): Record<string, string> {
  return {
    'user-agent': req.headers['user-agent'] ?? '',
    'accept-language': req.headers['accept-language'] ?? '',
    'x-forwarded-for': (req.headers['x-forwarded-for'] as string) ?? '',
    'x-real-ip': (req.headers['x-real-ip'] as string) ?? '',
  };
}

router.get('/locale', async (req: Request, res: Response) => {
  try {
    const headers = getHeaders(req);
    const geoContext = await fetchGeoContext(headers);
    const localization = resolveLocale(geoContext);
    res.json(localization);
  } catch (err) {
    console.error('Error resolving locale:', err);
    res.status(500).json({ error: 'Failed to resolve locale' });
  }
});

router.post('/locale', async (req: Request, res: Response) => {
  try {
    const body = req.body;
    const headers = getHeaders(req);
    const geoContext = await fetchGeoContext(headers, body);
    const localization = resolveLocale(geoContext);
    res.json(localization);
  } catch (err) {
    console.error('Error resolving locale:', err);
    res.status(500).json({ error: 'Failed to resolve locale' });
  }
});

export default router;
