module.exports = (sequelize, DataTypes) => {
  const StorageLocation = sequelize.define('StorageLocation', {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true
    },
    company_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'Company',
        key: 'id'
      }
    },
    plant_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'Plant',
        key: 'id'
      }
    },
    storage_location_code: {
      type: DataTypes.STRING(10),
      allowNull: false
    },
    description: {
      type: DataTypes.STRING(200),
      allowNull: false
    },
    storage_location_type: {
      type: DataTypes.ENUM('WAREHOUSE', 'PRODUCTION', 'QUALITY', 'SCRAP', 'BLOCKED', 'OTHER'),
      allowNull: true,
      defaultValue: 'WAREHOUSE'
    },
    address: {
      type: DataTypes.STRING(500),
      allowNull: true
    },
    status: {
      type: DataTypes.ENUM('ACTIVE', 'INACTIVE', 'BLOCKED'),
      allowNull: false,
      defaultValue: 'ACTIVE'
    },
    effective_from: {
      type: DataTypes.DATEONLY,
      allowNull: true
    },
    effective_to: {
      type: DataTypes.DATEONLY,
      allowNull: true
    },
    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: 'storage_location',
    indexes: [
      {
        unique: true,
        fields: ['company_id', 'plant_id', 'storage_location_code']
      },
      {
        fields: ['plant_id']
      },
      {
        fields: ['status']
      }
    ]
  });

  StorageLocation.associate = function(models) {
    StorageLocation.belongsTo(models.Company, { foreignKey: 'company_id', as: 'company' });
    StorageLocation.belongsTo(models.Plant, { foreignKey: 'plant_id', as: 'plant' });
    StorageLocation.belongsTo(models.User, { foreignKey: 'created_by', as: 'createdByUser' });
    StorageLocation.belongsTo(models.User, { foreignKey: 'updated_by', as: 'updatedByUser' });
  };

  return StorageLocation;
};

