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

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

      // fk
      company_id: {
        type: DataTypes.INTEGER,
        allowNull: true,
        references: {
          model: "companies",
          key: "id",
        },
      },
      territory_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        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",
        },
      },
    },
    {
      tableName: "salesplans",
      freezeTableName: true,
    }
  );

 SalesPlan.associate = function(models) {
   SalesPlan.belongsTo(models.Company, { foreignKey: "company_id", as: "company" }); 
   SalesPlan.belongsTo(models.Territory, { foreignKey: "territory_id", as: "territory" });
   SalesPlan.belongsTo(models.Period, { foreignKey: "period_id", as: "period" });
   SalesPlan.belongsTo(models.Year, { foreignKey: "year_id", as: "year" });
   SalesPlan.hasMany(models.SalesPlanItem, { foreignKey: "salesplan_id", as: "salesplanitems" });
 }
  return SalesPlan;
};
