const crud = require("../service/biz_admin_crud");
const { getRequestBody } = crud;
const baseModel = require("../../middleware/baseModel");
const logic = require("../service/biz_subscription_logic");
const audit = require("../service/biz_audit_service");

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);
    await audit.logAudit({
      admin_user_id: audit.pickAdminId(ctx),
      biz_user_id: body.user_id,
      action: "biz_subscription.open",
      resource_type: "biz_subscription",
      resource_id: row.id,
      detail: { plan_id: body.plan_id, status: row.status },
    });
    ctx.success(row);
  },
  "POST /biz_subscription/upgrade": async (ctx) => {
    const body = getRequestBody(ctx);
    const row = await logic.upgradeSubscription(body);
    await audit.logAudit({
      admin_user_id: audit.pickAdminId(ctx),
      action: "biz_subscription.upgrade",
      resource_type: "biz_subscription",
      resource_id: body.subscription_id,
      detail: { new_plan_id: body.new_plan_id },
    });
    ctx.success(row);
  },
  "POST /biz_subscription/renew": async (ctx) => {
    const body = getRequestBody(ctx);
    const row = await logic.renewSubscription(body);
    await audit.logAudit({
      admin_user_id: audit.pickAdminId(ctx),
      action: "biz_subscription.renew",
      resource_type: "biz_subscription",
      resource_id: body.subscription_id,
    });
    ctx.success(row);
  },
  "POST /biz_subscription/cancel": async (ctx) => {
    const body = getRequestBody(ctx);
    const row = await logic.cancelSubscription(body);
    await audit.logAudit({
      admin_user_id: audit.pickAdminId(ctx),
      action: "biz_subscription.cancel",
      resource_type: "biz_subscription",
      resource_id: body.subscription_id,
    });
    ctx.success(row);
  },
  "POST /biz_subscription/export": async (ctx) => {
    const body = getRequestBody(ctx);
    const res = await crud.exportCsv("biz_subscription", body);
    ctx.success(res);
  },
};
