import { Router, type Request, type Response } from 'express';
import { buildContext } from '../lib/context.js';

const router = Router();

interface ClientBody {
  geo?: {
    latitude?: number;
    longitude?: number;
    country?: string;
    countryCode?: string;
    region?: string;
    city?: string;
    timezone?: string;
  };
  client?: {
    screenWidth?: number;
    screenHeight?: number;
    viewportWidth?: number;
    viewportHeight?: number;
    devicePixelRatio?: number;
    timezone?: string;
    language?: string;
    languages?: string[];
    platform?: string;
    hardwareConcurrency?: number;
    deviceMemory?: number;
    cookieEnabled?: boolean;
    doNotTrack?: string | null;
  };
}

router.get('/context', (req: Request, res: Response) => {
  try {
    const context = buildContext(req);
    res.json(context);
  } catch (err) {
    console.error('Error building context:', err);
    res.status(500).json({ error: 'Failed to build context' });
  }
});

router.post('/context', (req: Request<object, object, ClientBody>, res: Response) => {
  try {
    const clientData = req.body;
    const context = buildContext(req, clientData);
    res.json(context);
  } catch (err) {
    console.error('Error building context:', err);
    res.status(500).json({ error: 'Failed to build context' });
  }
});

export default router;
