const { DataTypes } = require("sequelize");

module.exports = (sequelize) => {
  const WorkplanMonitors = sequelize.define(
    "workplanmonitor",
    {
      id: {
        type: DataTypes.INTEGER,
        autoIncrement: true,
        primaryKey: true,
      },
      creation: { type: DataTypes.DATE, allowNull: false },
      modified: { type: DataTypes.DATE, allowNull: false },
      modified_by: { type: DataTypes.INTEGER, allowNull: false },
      owner: { type: DataTypes.INTEGER, allowNull: false },
      enabled: { type: DataTypes.BOOLEAN, allowNull: false },

      name: {
        type: DataTypes.STRING(100),
        allowNull: false,
      },

      periode: { type: DataTypes.STRING(100), allowNull: true },
      compiler: { type: DataTypes.INTEGER, allowNull: true },
      date: { type: DataTypes.DATE, allowNull: true },
      counterpart: { type: DataTypes.STRING(100), allowNull: true },
      chat: { type: DataTypes.JSON, allowNull: true },


      //   fk
      company_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
          model: "companies",
          key: "id",
        },
      },
      owner_id: {
        type: DataTypes.INTEGER,
        allowNull: true,
        references: { model: "departments", key: "id" },
      },
      counterpart_id: {
        type: DataTypes.INTEGER,
        allowNull: true,
        references: { model: "departments", key: "id" },
      },
    },
    {
      tableName: "workplanmonitors",
      freezeTableName: true,
    }
  );

  /**
   * Associates the Province model with other models.
   * @param {object} models - The models to associate with.
   */
  WorkplanMonitors.associate = (models) => {
    /**
     * Associates the WorkplanMonitors model with the WorkplanMonitorChild model.
     * A DeliveryTrip has many DeliveryTripChilds.
     * @param {object} models - The models to associate with.
     */
    WorkplanMonitors.hasMany(models.WorkplanMonitorChild, {
      foreignKey: "workplanmonitor_id",
      as: "workplanmonitorchilds",
      onDelete: "CASCADE",
    });

    /**
     * Associates the WorkplanMonitors model with the Company model.
     * A DeliveryTrip belongs to a Company.
     * @param {object} models - The models to associate with.
     */
    WorkplanMonitors.belongsTo(models.Company, {
      foreignKey: "company_id",
      as: "company",
    });
    WorkplanMonitors.belongsTo(models.Department, {foreignKey: 'owner_id', as: 'owner_info'});
    WorkplanMonitors.belongsTo(models.Department, {foreignKey: 'counterpart_id', as: 'counterpart_info'});
  };

  return WorkplanMonitors;
};
