import http from 'node:http';
import { config } from './core/config.js';
import { applyCors, publicErrorBody, routeKey, sendJson } from './core/http.js';
import { createRouter } from './core/router.js';

const routes = createRouter();

function resolveHandler(method: string | undefined, url: URL) {
  const exact = routes.get(routeKey(method, url.pathname));
  if (exact) return exact;

  const questionVideosMatch = url.pathname.match(/^\/api\/questions\/([^/]+)\/videos$/);
  if (method === 'GET' && questionVideosMatch?.[1]) {
    url.searchParams.set('questionId', decodeURIComponent(questionVideosMatch[1]));
    return routes.get(routeKey(method, '/api/questions/videos'));
  }

  return null;
}

const server = http.createServer(async (req, res) => {
  applyCors(req, res);
  if (req.method === 'OPTIONS') {
    res.statusCode = 204;
    res.end();
    return;
  }

  const url = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`);
  const handler = resolveHandler(req.method, url);

  if (!handler) {
    sendJson(res, 404, { error: 'Not found', path: url.pathname });
    return;
  }

  try {
    const result = await handler({ req, res, url });
    sendJson(res, 200, result);
  } catch (error) {
    const { statusCode, body } = publicErrorBody(error);
    sendJson(res, statusCode, body);
  }
});

server.listen(config.port, () => {
  console.log(`[api] listening on http://127.0.0.1:${config.port}`);
});
