module.exports = (sequelize, DataTypes) => {
  const RouteCardOperationMaterialReversal = sequelize.define(
    'RouteCardOperationMaterialReversal',
    {
      id: {
        type: DataTypes.INTEGER,
        primaryKey: true,
        autoIncrement: true,
      },
      route_card_operation_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: { model: 'RouteCardOperation', key: 'id' },
      },
      production_order_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: { model: 'ProductionOrder', key: 'id' },
      },
      material_id: {
        type: DataTypes.INTEGER,
        allowNull: false,
        references: { model: 'Material', key: 'id' },
      },
      uom_id: {
        type: DataTypes.INTEGER,
        allowNull: true,
        references: { model: 'UOM', key: 'id' },
      },
      reversed_qty: {
        type: DataTypes.DECIMAL(18, 3),
        allowNull: false,
      },
      consumed_before_qty: {
        type: DataTypes.DECIMAL(18, 3),
        allowNull: false,
        defaultValue: 0,
      },
      consumed_after_qty: {
        type: DataTypes.DECIMAL(18, 3),
        allowNull: false,
        defaultValue: 0,
      },
      remarks: {
        type: DataTypes.STRING(500),
        allowNull: true,
      },
      created_by: {
        type: DataTypes.INTEGER,
        allowNull: true,
        references: { model: 'User', key: 'id' },
      },
    },
    {
      tableName: 'route_card_operation_material_reversal',
      timestamps: true,
      updatedAt: false,
      createdAt: 'created_at',
      indexes: [
        { fields: ['route_card_operation_id', 'material_id'] },
        { fields: ['production_order_id'] },
        { fields: ['created_at'] },
      ],
    }
  );

  RouteCardOperationMaterialReversal.associate = (models) => {
    RouteCardOperationMaterialReversal.belongsTo(models.RouteCardOperation, {
      foreignKey: 'route_card_operation_id',
      as: 'routeCardOperation',
    });
    RouteCardOperationMaterialReversal.belongsTo(models.ProductionOrder, {
      foreignKey: 'production_order_id',
      as: 'productionOrder',
    });
    RouteCardOperationMaterialReversal.belongsTo(models.Material, { foreignKey: 'material_id', as: 'material' });
    RouteCardOperationMaterialReversal.belongsTo(models.UOM, { foreignKey: 'uom_id', as: 'uom' });
    RouteCardOperationMaterialReversal.belongsTo(models.User, { foreignKey: 'created_by', as: 'createdByUser' });
  };

  return RouteCardOperationMaterialReversal;
};

