const Sequelize = require("sequelize");
const { Op } = Sequelize;
const baseModel = require("../../middleware/baseModel");

module.exports = {
  "GET /biz_dashboard/summary": async (ctx) => {
    const now = new Date();
    const in7 = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);

    const [
      userTotal,
      userActive,
      planActive,
      subPending,
      subActive,
      subExpired,
      tokenActive,
      renewSoon,
    ] = await Promise.all([
      baseModel.biz_user.count(),
      baseModel.biz_user.count({ where: { status: "active" } }),
      baseModel.biz_plan.count({ where: { status: "active" } }),
      baseModel.biz_subscription.count({ where: { status: "pending" } }),
      baseModel.biz_subscription.count({ where: { status: "active" } }),
      baseModel.biz_subscription.count({ where: { status: "expired" } }),
      baseModel.biz_api_token.count({ where: { status: "active" } }),
      baseModel.biz_subscription.count({
        where: {
          status: "active",
          end_time: { [Op.between]: [now, in7] },
        },
      }),
    ]);

    ctx.success({
      users: { total: userTotal, active: userActive },
      plans: { active: planActive },
      subscriptions: {
        pending: subPending,
        active: subActive,
        expired: subExpired,
        renew_within_7d: renewSoon,
      },
      tokens: { active: tokenActive },
      server_time: now.toISOString(),
    });
  },
};
