module.exports = (sequelize, DataTypes) => {
  const Routing = sequelize.define('Routing', {
    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'
      }
    },
    routing_number: {
      type: DataTypes.STRING(40),
      allowNull: false
    },
    material_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'Material',
        key: 'id'
      }
    },
    alternative: {
      type: DataTypes.STRING(2),
      allowNull: true,
      defaultValue: '01'
    },
    group_counter: {
      type: DataTypes.STRING(2),
      allowNull: true,
      defaultValue: '01'
    },
    base_quantity: {
      type: DataTypes.DECIMAL(15, 3),
      allowNull: false,
      defaultValue: 1.000
    },
    base_uom_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      references: {
        model: 'UOM',
        key: 'id'
      }
    },
    valid_from: {
      type: DataTypes.DATEONLY,
      allowNull: false
    },
    valid_to: {
      type: DataTypes.DATEONLY,
      allowNull: true
    },
    status: {
      type: DataTypes.ENUM('ACTIVE', 'INACTIVE', 'LOCKED'),
      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: 'routing',
    indexes: [
      {
        unique: true,
        fields: ['company_id', 'plant_id', 'routing_number', 'alternative', 'group_counter']
      },
      {
        fields: ['material_id']
      },
      {
        fields: ['plant_id']
      },
      {
        fields: ['status']
      },
      {
        fields: ['valid_from', 'valid_to']
      }
    ]
  });

  Routing.associate = function(models) {
    Routing.belongsTo(models.Company, { foreignKey: 'company_id', as: 'company' });
    Routing.belongsTo(models.Plant, { foreignKey: 'plant_id', as: 'plant' });
    Routing.belongsTo(models.Material, { foreignKey: 'material_id', as: 'material' });
    Routing.hasMany(models.RoutingOperation, { foreignKey: 'routing_id', as: 'operations' });
    Routing.belongsTo(models.UOM, { foreignKey: 'base_uom_id', as: 'baseUOM' });
  };

  return Routing;
};

