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

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

      posting_no: {
        type: DataTypes.STRING(100),
        allowNull: false,
        unique: true,
      },
      title: {
        type: DataTypes.STRING(100),
        allowNull: false,
      },
      responsibility: { type: DataTypes.TEXT, allowNull: true },
      qualification: { type: DataTypes.TEXT, allowNull: true },

      //   fk
      designation_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
          model: "designations",
          key: "id",
        },
      },
      city_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
          model: "cities",
          key: "id",
        },
      },
      province_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
          model: "provinces",
          key: "id",
        },
      },
      company_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
          model: "companies",
          key: "id",
        },
      },
    },
    {
      tableName: "jobpostings",
      freezeTableName: true,
    }
  );

  /**
   * Associates the Province model with other models.
   * @param {object} models - The models to associate with.
   */
  JobPostings.associate = (models) => {
    /**
     * Associates the JobPostings model with the JobPostingChild model.
     * A JobPosting has many JobPostingChild.
     * @param {object} models - The models to associate with.
     */
    JobPostings.hasMany(models.JobPostingChild, {
      foreignKey: "jobposting_id",
      as: "jobpostingchilds",
      onDelete: "CASCADE",
    });

    /**
     * Associates the JobPostings model with the Company model.
     * A JobPosting belongs to a Company.
     * @param {object} models - The models to associate with.
     */
    JobPostings.belongsTo(models.Company, {
      foreignKey: "company_id",
      as: "company",
    });

    JobPostings.belongsTo(models.Province, {
      foreignKey: "province_id",
      as: "province",
    });
    JobPostings.belongsTo(models.City, { foreignKey: "city_id", as: "city" });
    JobPostings.belongsTo(models.User, { foreignKey: "owner", as: "user" });
    JobPostings.belongsTo(models.Designation, { foreignKey: 'designation_id', as: 'designation' });
    JobPostings.hasMany(models.Applicant, { foreignKey: 'jobposting_id', as: 'applicants' });
  };

  return JobPostings;
};
