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

module.exports = (sequelize) => {
  const JobPostingChild = sequelize.define(
    "jobpostingchild",
    {
      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,
      },
      applicant_name: {
        type: DataTypes.STRING(100),
        allowNull: false,
      },
      //fk
      jobposting_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
          model: "jobpostings",
          key: "id",
        },
      },
      employeerequest_id: {
        type: DataTypes.INTEGER,
        allowNull: true,
        references: { model: "employeerequests", key: "id" },
      },
      applicant_id: {
        type: DataTypes.INTEGER,
        allowNull: true,
        references: { model: "applicants", key: "id" },
      },
    },
    {
      tableName: "jobpostingchilds",
      freezeTableName: true,
    }
  );

  /**
   * Associates the JobPostingChild model with other models.
   * @param {object} models - The models to associate with.
   * @description
   *   - A JobPostingChild belongs to a JobPosting.
   */
  JobPostingChild.associate = (models) => {
    /**
     * Associates the JobPostingChild model with the JobPosting model.
     * A JobPostingChild belongs to a JobPosting.
     * @param {object} models - The models to associate with.
     */
    JobPostingChild.belongsTo(models.JobPosting, {
      foreignKey: "jobposting_id",
      as: "jobposting",
    });

    JobPostingChild.belongsTo(models.EmployeeRequest, {
      foreignKey: "employeerequest_id",
      as: "employeerequest",
    });

    JobPostingChild.belongsTo(models.Applicant, {
      foreignKey: "applicant_id",
      as: "applicant",
    });
    JobPostingChild.belongsTo(models.User, { foreignKey: 'owner', as: 'user' });
  };

  return JobPostingChild;
};
