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

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

      // fk
      salesplan_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
          model: "salesplans",
          key: "id",
        },
      },
      customer_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
          model: "customerlists",
          key: "id",
        },
      },
      item_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: {
          model: "items",
          key: "id",
        },
      },

      quantity: { type: DataTypes.INTEGER, allowNull: true },
      price: { type: DataTypes.INTEGER, allowNull: true },
      total_gross: { type: DataTypes.INTEGER, allowNull: true },
      discount: { type: DataTypes.INTEGER, allowNull: true },
      nett_price: { type: DataTypes.INTEGER, allowNull: true },
      total_estimate: { type: DataTypes.INTEGER, allowNull: true },
      distributor: { type: DataTypes.STRING(100), allowNull: true },
      progress: {type: DataTypes.STRING(50), allowNull: true},
      remarks: { type: DataTypes.TEXT, allowNull: true },
    },
    {
      tableName: "salesplanitems",
      freezeTableName: true,
    }
  );

 SalesPlanItem.associate = function(models) {
   SalesPlanItem.belongsTo(models.SalesPlan, { foreignKey: "salesplan_id", as: "salesplan", onDelete: "CASCADE" });
   SalesPlanItem.belongsTo(models.CustomerList, { foreignKey: "customer_id", as: "customer" });
   SalesPlanItem.belongsTo(models.Item, { foreignKey: "item_id", as: "item" }); 
   SalesPlanItem.hasMany(models.SalesPlanEstimate, { foreignKey: "salesplanitem_id", as: "salesplanestimates" });
 }
  return SalesPlanItem;
};
