/**
 * LiteMall 并发监控
 * 
 * 监测短时间内的请求和订单量
 * 超过阈值时在后台Dashboard提示升级建议
 */

const { get, run } = require('../utils/db');

const ORDER_WARN_THRESHOLD = 30;   // 30单/分钟 → 弹窗警告
const ORDER_CRIT_THRESHOLD = 60;   // 60单/分钟 → 强烈建议升级

const metrics = {
  ordersLastMinute: [],
  requestsLastMinute: [],
  startTime: Date.now(),
};

/**
 * 记录订单
 */
    // NOTE: trackOrder 仅一次 push + filter，对 60s 滑动窗口而言无性能瓶颈

function trackOrder() {
  const now = Date.now();
  metrics.ordersLastMinute.push(now);
  // 清理超过1分钟的记录
  metrics.ordersLastMinute = metrics.ordersLastMinute.filter(t => now - t < 60000);
}

/**
 * 记录请求
 */
function trackRequest() {
  const now = Date.now();
  metrics.requestsLastMinute.push(now);
  metrics.requestsLastMinute = metrics.requestsLastMinute.filter(t => now - t < 60000);
}

/**
 * 获取当前并发状态
 */
function getStatus() {
  const orderRate = metrics.ordersLastMinute.length;
  const reqRate = metrics.requestsLastMinute.length;
  const uptime = Math.floor((Date.now() - metrics.startTime) / 1000);
  
  const status = {
    order_rate: orderRate,
    request_rate: reqRate,
    uptime_seconds: uptime,
    level: 'normal',
    message: '',
    upgrade_suggest: null,
  };

  if (orderRate >= ORDER_CRIT_THRESHOLD) {
    status.level = 'critical';
    status.message = `当前下单频率${orderRate}单/分钟，超过SQLite承载上限（建议60单/分钟以内）`;
    status.upgrade_suggest = {
      title: '⚠️ 当前访问量较高',
      content: `每分钟订单量已达 ${orderRate} 单，接近SQLite轻量版的承载上限。大促、独立站流量场景建议升级MySQL商用版，支持十倍并发不卡顿。`,
      action_text: '查看升级方案',
      action_url: '#/settings?tab=upgrade',
    };
  } else if (orderRate >= ORDER_WARN_THRESHOLD) {
    status.level = 'warning';
    status.message = `当前下单频率${orderRate}单/分钟，接近SQLite轻量版推荐上限`;
    status.upgrade_suggest = {
      title: '📈 流量增长提示',
      content: `每分钟订单量 ${orderRate} 单，SQLite轻量版稳定建议控制在 ${ORDER_WARN_THRESHOLD} 单/分钟以内。如持续增长，建议升级MySQL商用版。`,
      action_text: '了解升级方案',
      action_url: '#/settings?tab=upgrade',
    };
  }

  return status;
}

/**
 * 获取今日订单总览（含升级建议）
 */
function getDashboardHint() {
  try {
    const todayCount = get("SELECT COUNT(*) as c FROM orders WHERE date(created_at)=date('now','localtime')");
    const todayOrders = todayCount?.c || 0;
    const remaining = Math.max(0, ORDER_WARN_THRESHOLD * 60 - todayOrders);
    
    return {
      today_orders: todayOrders,
      daily_recommended_max: ORDER_WARN_THRESHOLD * 60, // 1800单/天
      remaining_capacity: remaining,
      upgrade_recommended: todayOrders > ORDER_CRIT_THRESHOLD * 60,
    };
  } catch (e) {
    return { today_orders: 0, daily_recommended_max: 1800, remaining_capacity: 1800 };
  }
}

module.exports = { trackOrder, trackRequest, getStatus, getDashboardHint };
