const crud = require("../service/biz_admin_crud");
const baseModel = require("../../middleware/baseModel");
const logic = require("../service/biz_subscription_logic");

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_subscription/page": async (ctx) => {
    const body = getRequestBody(ctx);
    const data = await crud.page("biz_subscription", body);
    ctx.success({ rows: data.rows, count: data.count });
  },
  "GET /biz_subscription/detail": async (ctx) => {
    const q = ctx.query || {};
    const row = await crud.detail("biz_subscription", { id: q.id || q.ID });
    ctx.success(row);
  },
  "GET /biz_subscription/by_user": async (ctx) => {
    const q = ctx.query || {};
    const user_id = q.user_id || q.userId;
    if (!user_id) return ctx.fail("缺少 user_id");
    const rows = await baseModel.biz_subscription.findAll({
      where: { user_id },
      order: [["id", "DESC"]],
    });
    ctx.success(rows);
  },
  "POST /biz_subscription/open": async (ctx) => {
    const body = getRequestBody(ctx);
    const row = await logic.openSubscription(body);
    ctx.success(row);
  },
  "POST /biz_subscription/upgrade": async (ctx) => {
    const body = getRequestBody(ctx);
    const row = await logic.upgradeSubscription(body);
    ctx.success(row);
  },
  "POST /biz_subscription/renew": async (ctx) => {
    const body = getRequestBody(ctx);
    const row = await logic.renewSubscription(body);
    ctx.success(row);
  },
  "POST /biz_subscription/cancel": async (ctx) => {
    const body = getRequestBody(ctx);
    const row = await logic.cancelSubscription(body);
    ctx.success(row);
  },
};
