const stats = require("../service/biz_api_stats_service");
const crud = require("../service/biz_admin_crud");

function getRequestBody(ctx) {
  if (ctx.request && ctx.request.body && Object.keys(ctx.request.body).length > 0) {
    return ctx.request.body;
  }
  if (typeof ctx.getBody === "function") {
    return ctx.getBody() || {};
  }
  return {};
}

module.exports = {
  /** 按用户查询调用统计 */
  "POST /biz_api_stats/by_user": async (ctx) => {
    const body = getRequestBody(ctx);
    const { user_id, start_date, end_date } = body;
    if (!user_id) {
      ctx.fail("缺少 user_id");
      return;
    }
    const data = await stats.getStatsByUser(user_id, start_date, end_date);
    ctx.success(data);
  },

  /** 按接口路径查询调用统计 */
  "POST /biz_api_stats/by_api": async (ctx) => {
    const body = getRequestBody(ctx);
    const { api_path, start_date, end_date } = body;
    if (!api_path) {
      ctx.fail("缺少 api_path");
      return;
    }
    const data = await stats.getStatsByApi(api_path, start_date, end_date);
    ctx.success(data);
  },

  /** 综合统计面板 */
  "POST /biz_api_stats/summary": async (ctx) => {
    const body = getRequestBody(ctx);
    const { start_date, end_date, top_limit } = body;
    const data = await stats.getSummary(start_date, end_date, top_limit || 10);
    ctx.success(data);
  },

  /** 调用日志分页列表（复用通用 CRUD） */
  "POST /biz_api_call_log/page": async (ctx) => {
    const body = getRequestBody(ctx);
    const data = await crud.page("biz_api_call_log", body);
    ctx.success({ rows: data.rows, count: data.count });
  },
};
