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

module.exports = (sequelize) => {
  const Period = sequelize.define(
    "period",
    {
      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 },

      display_name: { type: DataTypes.STRING(100), allowNull: false },
      start_date: { type: DataTypes.DATEONLY, allowNull: false },
      end_date: { type: DataTypes.DATEONLY, allowNull: false },

      // fk
      year_id: { type: DataTypes.INTEGER, allowNull: false, references: { model: 'Years', key: 'id' } },
    },
    {
      tableName: "periods",
      freezeTableName: true,
    }
  );

  /**
   * Associates the Period model with other models.
   * @param {object} models - The models to associate with.
   */
  Period.associate = (models) => { 
    Period.belongsTo(models.Year, { foreignKey: "year_id", as: "year" });
    Period.hasMany(models.CallPlan, { foreignKey: "period_id", as: "callplans" });
    Period.hasMany(models.SalesDistributor, { foreignKey: "period_id", as: "salesdistributors" });
    Period.hasMany(models.ImportSalesDistributor, { foreignKey: "period_id", as: "importsalesdistributors" });
    Period.hasMany(models.Survey, { foreignKey: "period_id", as: "surveys" });
    Period.hasMany(models.SalesTarget, { foreignKey: "period_id", as: "salestargets" });

  };

  return Period;
};
