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

module.exports = (sequelize) => {
  const Fses = sequelize.define(
    "fse",
    {
      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,
        unique: true,
      },

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

  /**
   * Associates the Customer List model with other models.
   * @param {object} models - The models to associate with.
   */
  Fses.associate = (models) => {
    /**
     * Associates the Fses model with the UdkProduct model.
     * A Fse has many UdkProducts.
     * @param {object} models - The models to associate with.
     */
    Fses.hasMany(models.FseItem, {
      foreignKey: "fse_id",
      as: "fseitems",
      onDelete: "CASCADE",
    });

    /**
     * Associates the Fses model with the Territory model.
     * A Fse belongs to a Territory.
     * @param {object} models - The models to associate with.
     */
    Fses.belongsTo(models.Territory, {
      foreignKey: "territory_id",
      as: "territory",
    });
    /**
     * Associates the Fses model with the Period model.
     * A Fse belongs to a Period.
     * @param {object} models - The models to associate with.
     */
    Fses.belongsTo(models.Period, { foreignKey: "period_id", as: "period" });
    /**
     * Associates the Fses model with the Year model.
     * A Year belongs to a Company.
     * @param {object} models - The models to associate with.
     */
    Fses.belongsTo(models.Year, { foreignKey: "year_id", as: "year" });
    /**
     * Associates the Fses model with the Company model.
     * A Fse belongs to a Company.
     * @param {object} models - The models to associate with.
     */
    Fses.belongsTo(models.Company, {
      foreignKey: "company_id",
      as: "company",
    });

    Fses.belongsTo(models.User, { foreignKey: "owner", as: "user" });
  };

  return Fses;
};
