const baseModel = require("../../middleware/baseModel");
const { build_search_where, normalize_for_write } = require("../utils/query_helpers");

module.exports = {
  "POST /biz_usage/page": async (ctx) => {
    const body = ctx.getBody();
    const param = body.param || body;
    const page_option = param.pageOption || {};
    const seach_option = param.seachOption || {};
    const page_num = parseInt(page_option.page, 10) || 1;
    const page_size = parseInt(page_option.pageSize, 10) || 20;
    const offset = (page_num - 1) * page_size;
    const biz_usage_monthly = baseModel.biz_usage_monthly;
    const where = build_search_where(biz_usage_monthly, seach_option);
    const { count, rows } = await biz_usage_monthly.findAndCountAll({
      where,
      offset,
      limit: page_size,
      order: [["id", "DESC"]],
    });
    ctx.success({ rows, count });
  },
  "POST /biz_usage/add": async (ctx) => {
    const body = ctx.getBody();
    const payload = normalize_for_write(baseModel.biz_usage_monthly, body, { for_create: true });
    const row = await baseModel.biz_usage_monthly.create(payload);
    ctx.success(row);
  },
  "POST /biz_usage/edit": async (ctx) => {
    const body = ctx.getBody();
    const id = body.id;
    if (id === undefined || id === null || id === "") throw new Error("缺少 id");
    const payload = normalize_for_write(baseModel.biz_usage_monthly, body, { for_create: false });
    delete payload.id;
    await baseModel.biz_usage_monthly.update(payload, { where: { id } });
    ctx.success({});
  },
  "POST /biz_usage/del": async (ctx) => {
    const body = ctx.getBody();
    const id = body.id !== undefined ? body.id : body;
    if (id === undefined || id === null || id === "") throw new Error("缺少 id");
    await baseModel.biz_usage_monthly.destroy({ where: { id } });
    ctx.success({});
  },
  "GET /biz_usage/detail": async (ctx) => {
    const q = ctx.query || {};
    const id = q.id || q.ID;
    if (id === undefined || id === null || id === "") throw new Error("缺少 id");
    const row = await baseModel.biz_usage_monthly.findByPk(id);
    ctx.success(row);
  },
  "POST /biz_usage/export": async (ctx) => {
    const body = ctx.getBody();
    const param = body.param || body;
    const biz_usage_monthly = baseModel.biz_usage_monthly;
    const where = build_search_where(biz_usage_monthly, param.seachOption || {});
    const rows = await biz_usage_monthly.findAll({
      where,
      limit: 10000,
      order: [["id", "DESC"]],
    });
    ctx.success({ rows });
  },
};
