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

module.exports = {
  "POST /biz_plan/page": async (ctx) => {
    const body = getRequestBody(ctx);
    const data = await crud.page("biz_plan", body);
    ctx.success({ rows: data.rows, count: data.count });
  },
  "POST /biz_plan/add": async (ctx) => {
    const body = getRequestBody(ctx);
    const row = await crud.add("biz_plan", body);
    await audit.logAudit({
      admin_user_id: audit.pickAdminId(ctx),
      action: "biz_plan.add",
      resource_type: "biz_plan",
      resource_id: row.id,
      detail: { plan_code: row.plan_code },
    });
    ctx.success(row);
  },
  "POST /biz_plan/edit": async (ctx) => {
    const body = getRequestBody(ctx);
    await crud.edit("biz_plan", body);
    await audit.logAudit({
      admin_user_id: audit.pickAdminId(ctx),
      action: "biz_plan.edit",
      resource_type: "biz_plan",
      resource_id: body.id,
    });
    ctx.success({});
  },
  "POST /biz_plan/del": async (ctx) => {
    const body = getRequestBody(ctx);
    await crud.del("biz_plan", body);
    await audit.logAudit({
      admin_user_id: audit.pickAdminId(ctx),
      action: "biz_plan.del",
      resource_type: "biz_plan",
      resource_id: body.id,
    });
    ctx.success({});
  },
  "GET /biz_plan/detail": async (ctx) => {
    const q = ctx.query || {};
    const row = await crud.detail("biz_plan", { id: q.id || q.ID });
    ctx.success(row);
  },
  "GET /biz_plan/all": async (ctx) => {
    const rows = await crud.all("biz_plan");
    ctx.success(rows);
  },
  "POST /biz_plan/toggle": async (ctx) => {
    const body = getRequestBody(ctx);
    const id = body.id;
    if (id == null) return ctx.fail("缺少 id");
    const row = await baseModel.biz_plan.findByPk(id);
    if (!row) return ctx.fail("套餐不存在");
    const next = row.status === "active" ? "inactive" : "active";
    await row.update({ status: next });
    await audit.logAudit({
      admin_user_id: audit.pickAdminId(ctx),
      action: "biz_plan.toggle",
      resource_type: "biz_plan",
      resource_id: id,
      detail: { status: next },
    });
    ctx.success({ status: next });
  },
  "POST /biz_plan/export": async (ctx) => {
    const body = getRequestBody(ctx);
    const res = await crud.exportCsv("biz_plan", body);
    ctx.success(res);
  },
};
