const baseModel = require("../../middleware/baseModel");
const { op } = baseModel;

/**
 * 构建日期范围 where 条件
 */
function buildDateWhere(start_date, end_date) {
  const where = {};
  if (start_date && end_date) {
    where.call_date = { [op.between]: [start_date, end_date] };
  } else if (start_date) {
    where.call_date = { [op.gte]: start_date };
  } else if (end_date) {
    where.call_date = { [op.lte]: end_date };
  }
  return where;
}

/**
 * 按用户统计调用量（按接口路径分组）
 * @param {number} user_id
 * @param {string} [start_date] - YYYY-MM-DD
 * @param {string} [end_date]   - YYYY-MM-DD
 */
async function getStatsByUser(user_id, start_date, end_date) {
  const where = { user_id, ...buildDateWhere(start_date, end_date) };
  const rows = await baseModel.biz_api_call_log.findAll({
    attributes: [
      "api_path",
      [baseModel.Sequelize.fn("COUNT", baseModel.Sequelize.col("id")), "call_count"],
      [baseModel.Sequelize.fn("AVG", baseModel.Sequelize.col("response_time")), "avg_response_time"],
    ],
    where,
    group: ["api_path"],
    order: [[baseModel.Sequelize.literal("call_count"), "DESC"]],
    raw: true,
  });

  const total = rows.reduce((s, r) => s + Number(r.call_count), 0);
  return { total, rows };
}

/**
 * 按接口路径统计调用量（按用户分组）
 * @param {string} api_path
 * @param {string} [start_date]
 * @param {string} [end_date]
 */
async function getStatsByApi(api_path, start_date, end_date) {
  const where = { api_path, ...buildDateWhere(start_date, end_date) };
  const rows = await baseModel.biz_api_call_log.findAll({
    attributes: [
      "user_id",
      [baseModel.Sequelize.fn("COUNT", baseModel.Sequelize.col("id")), "call_count"],
      [baseModel.Sequelize.fn("AVG", baseModel.Sequelize.col("response_time")), "avg_response_time"],
    ],
    where,
    group: ["user_id"],
    order: [[baseModel.Sequelize.literal("call_count"), "DESC"]],
    raw: true,
  });

  const total = rows.reduce((s, r) => s + Number(r.call_count), 0);
  return { total, rows };
}

/**
 * 综合统计面板：总调用量、按天趋势、Top 接口、Top 用户
 * @param {string} [start_date]
 * @param {string} [end_date]
 * @param {number} [top_limit=10]
 */
async function getSummary(start_date, end_date, top_limit = 10) {
  const dateWhere = buildDateWhere(start_date, end_date);
  const Seq = baseModel.Sequelize;

  // 总调用量
  const totalResult = await baseModel.biz_api_call_log.count({ where: dateWhere });

  // 按天趋势
  const daily_trend = await baseModel.biz_api_call_log.findAll({
    attributes: [
      "call_date",
      [Seq.fn("COUNT", Seq.col("id")), "call_count"],
    ],
    where: dateWhere,
    group: ["call_date"],
    order: [["call_date", "ASC"]],
    raw: true,
  });

  // Top 接口
  const top_apis = await baseModel.biz_api_call_log.findAll({
    attributes: [
      "api_path",
      [Seq.fn("COUNT", Seq.col("id")), "call_count"],
    ],
    where: dateWhere,
    group: ["api_path"],
    order: [[Seq.literal("call_count"), "DESC"]],
    limit: top_limit,
    raw: true,
  });

  // Top 用户
  const top_users = await baseModel.biz_api_call_log.findAll({
    attributes: [
      "user_id",
      [Seq.fn("COUNT", Seq.col("id")), "call_count"],
    ],
    where: dateWhere,
    group: ["user_id"],
    order: [[Seq.literal("call_count"), "DESC"]],
    limit: top_limit,
    raw: true,
  });

  return {
    total_calls: totalResult,
    daily_trend,
    top_apis,
    top_users,
  };
}

module.exports = { getStatsByUser, getStatsByApi, getSummary };
