module.exports = (sequelize, DataTypes) => {
  const Plant = sequelize.define('Plant', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    company_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'Company',
        key: 'id'
      }
    },
    code: {
      type: DataTypes.STRING(20),
      allowNull: false
    },
    name: {
      type: DataTypes.STRING(200),
      allowNull: false
    },
    plant_type: {
      type: DataTypes.ENUM('MANUFACTURING', 'WAREHOUSE', 'SALES_OFFICE', 'SERVICE_CENTER'),
      allowNull: false,
      defaultValue: 'MANUFACTURING'
    },
    address_line1: {
      type: DataTypes.STRING(200),
      allowNull: true
    },
    address_line2: {
      type: DataTypes.STRING(200),
      allowNull: true
    },
    city_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'City',
        key: 'id'
      }
    },
    state_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'State',
        key: 'id'
      }
    },
    country_id: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'Country',
        key: 'id'
      }
    },
    pincode: {
      type: DataTypes.STRING(10),
      allowNull: true
    },
    phone: {
      type: DataTypes.STRING(20),
      allowNull: true
    },
    email: {
      type: DataTypes.STRING(100),
      allowNull: true
    },
    status: {
      type: DataTypes.ENUM('ACTIVE', 'INACTIVE', 'SUSPENDED'),
      allowNull: false,
      defaultValue: 'ACTIVE'
    },
    created_by: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'User',
        key: 'id'
      }
    },
    updated_by: {
      type: DataTypes.INTEGER,
      allowNull: true,
      references: {
        model: 'User',
        key: 'id'
      }
    }
  }, {
    tableName: 'plant',
    indexes: [
      {
        unique: true,
        fields: ['company_id', 'code']
      },
      {
        fields: ['status']
      },
      {
        fields: ['plant_type']
      }
    ]
  });

  Plant.associate = function(models) {
    Plant.belongsTo(models.Company, { foreignKey: 'company_id', as: 'company' });
    Plant.hasMany(models.GSTIN, { foreignKey: 'plant_id', as: 'gstins' });
    Plant.belongsTo(models.City, { foreignKey: 'city_id', as: 'city' });
    Plant.belongsTo(models.State, { foreignKey: 'state_id', as: 'state' });
    Plant.belongsTo(models.Country, { foreignKey: 'country_id', as: 'country' });
  };

  return Plant;
};

