// api/<service-name>/[...path].ts
import type { VercelRequest, VercelResponse } from '@vercel/node';
// Allowed operations — one handler per path
const ROUTES: Record<string, (req: VercelRequest) => Promise<unknown>> = {
  // 'GET /contacts': handleGetContacts,
  // 'POST /contacts': handleCreateContact,
};

export default async function handler(req: VercelRequest, res: VercelResponse) {
  const path = Array.isArray(req.query.path)
    ? req.query.path.join('/')
    : req.query.path ?? '';

  const routeKey = `${req.method} /${path}`;
  const routeHandler = ROUTES[routeKey];

  if (!routeHandler) {
    return res.status(404).json({ error: 'Not found' });
  }

  try {
    const data = await routeHandler(req);
    return res.status(200).json(data);
  } catch (error) {
    console.error(`[api/<service-name>] ${routeKey} failed:`, error);
    return res.status(500).json({ error: 'Internal server error' });
  }
}

// Example fetch-based handler:
// async function handleGetContacts(req: VercelRequest) {
//   const API_KEY = process.env.<SERVICE>_API_KEY;
//   if (!API_KEY) throw new Error('Missing API key');
//
//   const controller = new AbortController();
//   const timeout = setTimeout(() => controller.abort(), 10_000);
//
//   try {
//     const response = await fetch('https://api.example.com/contacts', {
//       headers: { Authorization: `Bearer ${API_KEY}` },
//       signal: controller.signal,
//     });
//     if (!response.ok) throw new Error(`Upstream ${response.status}`);
//     const raw = await response.json();
//     return raw.results.map((c: any) => ({ id: c.id, name: c.name, email: c.email }));
//   } finally {
//     clearTimeout(timeout);
//   }
// }
