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

module.exports = (sequelize) => {
  const Survey = sequelize.define(
    "survey",
    {
      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: true },
      owner: { type: DataTypes.INTEGER, allowNull: true },
      enabled: { type: DataTypes.BOOLEAN, allowNull: false },

      doc_no: { type: DataTypes.STRING(100), allowNull: false },
      status: { type: DataTypes.INTEGER, allowNull: true },

      // fk
      company_id: { type: DataTypes.INTEGER, allowNull: false, references: {model: "companies",key: "id"}},
      territory_id: { type: DataTypes.INTEGER, allowNull: false, references: { model: "territories", key: "id" } },
      period_id:  { type: DataTypes.INTEGER, allowNull: false, references: { model: "periods", key: "id" } },
      year_id:  { type: DataTypes.INTEGER, allowNull: false, references: { model: "years", key: "id" } },
      period_id:  { type: DataTypes.INTEGER, allowNull: false, references: { model: "periods", key: "id" } },
    },
    {
      tableName: "surveys",
      freezeTableName: true,
    }
  );

  /**
   * Associates the CallPlan model with other models. 
   * @param {object} models - The models to associate with.
   */
  Survey.associate = (models) => {
    Survey.belongsTo(models.Company, { foreignKey: "company_id", as: "company" });
    Survey.belongsTo(models.Territory, { foreignKey: "territory_id", as: "territory" });
    Survey.belongsTo(models.Year, { foreignKey: "year_id", as: "year" });
    Survey.belongsTo(models.Period, { foreignKey: "period_id", as: "period" });
    Survey.hasMany(models.SurveySellingIn, { foreignKey: "survey_id", as: "surveysellingins", onDelete: "CASCADE" });
    Survey.hasMany(models.SurveyExpense, { foreignKey: "survey_id", as: "surveyexpenses", onDelete: "CASCADE" });
    Survey.hasMany(models.SurveyTreatment, { foreignKey: "survey_id", as: "surveytreatments", onDelete: "CASCADE" });
  };


  return Survey;
};
