const dayjs = require('dayjs');

module.exports = () => {
  return async (ctx, next) => {
    // 跳过静态资源和source map
    if (ctx.path.startsWith('/static/') || ctx.path === '/favicon.ico') {
      return next();
    }
    // source map / json 静态请求直接返回 404，避免 think-trace 报错
    if (ctx.path.endsWith('.map') || ctx.path.endsWith('.json')) {
      ctx.status = 404;
      ctx.body = '';
      return;
    }

    const start = Date.now();
    const params = { ...ctx.query, ...(ctx.request.body || {}) };

    try {
      await next();
    } catch (e) {
      throw e;
    } finally {
      // 只打印 JSON 接口响应（this.success / this.fail / this.json）
      const body = ctx.body;
      const isJson = body && typeof body === 'object' && ('code' in body || 'errno' in body || 'data' in body);
      if (isJson) {
        const elapsed = ((Date.now() - start) / 1000).toFixed(3);
        const result = JSON.stringify(body).slice(0, 500);
        const log = [
          '=================== 请求日志 ===================',
          `path: ${ctx.path}`,
          `method: ${ctx.method}`,
          `params: ${JSON.stringify(params)}`,
          `result: ${result}`,
          `time: ${dayjs().format('YYYY-MM-DD HH:mm:ss')}`,
          `耗时: ${elapsed}秒`,
          '=================== 请求结束 ===================',
        ].join('\n');
        console.log(log);
      }
    }
  };
};
