import type { MiddlewareHandler } from 'hono';
import type { Env } from '../env';
import { ulid } from '../utils/id';

export const requestLogger: MiddlewareHandler<Env> = async (c, next) => {
  const requestId = ulid();
  c.set('requestId', requestId);
  const start = Date.now();
  await next();
  c.header('X-Request-Id', requestId);
  const duration = Date.now() - start;
  if (duration > 1500 || c.res.status >= 500) {
    console.log(JSON.stringify({ requestId, method: c.req.method, path: c.req.path, status: c.res.status, duration }));
  }
};
