/**
 * 管理端：筛选条件、写入字段裁剪（分页/导出在各 controller 内直接 findAndCountAll / findAll）
 */
const Sequelize = require("sequelize");
const { Op } = Sequelize;

function build_search_where(model, seach_option) {
  const key = seach_option && seach_option.key;
  const raw = seach_option && seach_option.value;
  if (!key || raw === undefined || raw === null) return {};
  const str = String(raw).trim();
  if (str === "") return {};

  const attr = model.rawAttributes[key];
  if (!attr) {
    return { [key]: { [Op.like]: `%${str}%` } };
  }

  const type_key = attr.type && attr.type.key;

  if (type_key === "BOOLEAN") {
    if (str === "true" || str === "1" || str === "是") return { [key]: true };
    if (str === "false" || str === "0" || str === "否") return { [key]: false };
    return {};
  }

  if (type_key === "ENUM") {
    return { [key]: str };
  }

  if (
    type_key === "INTEGER" ||
    type_key === "BIGINT" ||
    type_key === "FLOAT" ||
    type_key === "DOUBLE" ||
    type_key === "DECIMAL"
  ) {
    const n = Number(str);
    if (!Number.isNaN(n)) return { [key]: n };
    return {};
  }

  if (type_key === "DATE" || type_key === "DATEONLY") {
    return { [key]: str };
  }

  return { [key]: { [Op.like]: `%${str}%` } };
}

function normalize_for_write(model, data, { for_create } = {}) {
  const attrs = model.rawAttributes;
  const out = {};
  for (const k of Object.keys(data || {})) {
    if (!attrs[k]) continue;
    let v = data[k];
    if (v === "") {
      if (k === "id" && for_create) continue;
      if (k.endsWith("_id") || k === "id") {
        v = null;
      } else if (attrs[k].allowNull) {
        v = null;
      }
    }
    if (k === "enabled_features" && typeof v === "string" && v.trim() !== "") {
      try {
        v = JSON.parse(v);
      } catch (e) {
        /* 保持原字符串 */
      }
    }
    out[k] = v;
  }
  if (for_create && out.id !== undefined && (out.id === "" || out.id === null)) {
    delete out.id;
  }
  return out;
}

module.exports = {
  build_search_where,
  normalize_for_write,
};
