const Sequelize = require("sequelize");

/** 模板示例：与库表字段 create_time / last_modify_time / is_delete 一致（无 createdAt/updatedAt） */
module.exports = (db) => {
  return db.define(
    "tpl_demo",
    {
      title: {
        type: Sequelize.STRING(200),
        allowNull: false,
        comment: "标题",
      },
      remark: {
        type: Sequelize.STRING(500),
        allowNull: true,
        comment: "备注",
      },
      create_time: {
        type: Sequelize.DATE,
        allowNull: false,
        comment: "创建时间",
      },
      last_modify_time: {
        type: Sequelize.DATE,
        allowNull: false,
        comment: "最后修改时间",
      },
      is_delete: {
        type: Sequelize.INTEGER(1),
        allowNull: false,
        defaultValue: 0,
        comment: "0 正常 1 已删除",
      },
    },
    {
      comment: "前后端模板演示表",
      timestamps: false,
      defaultScope: {
        where: { is_delete: 0 },
      },
      hooks: {
        beforeCreate(instance) {
          const now = new Date();
          if (!instance.get("create_time")) {
            instance.set("create_time", now);
          }
          if (!instance.get("last_modify_time")) {
            instance.set("last_modify_time", now);
          }
          if (instance.get("is_delete") == null) {
            instance.set("is_delete", 0);
          }
        },
        beforeUpdate(instance) {
          instance.set("last_modify_time", new Date());
        },
      },
    }
  );
};
