module.exports = (sequelize, DataTypes) => {
  const RouteCardOperationComponentTracking = sequelize.define(
    'RouteCardOperationComponentTracking',
    {
      id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
      route_card_id: { type: DataTypes.INTEGER, allowNull: false },
      route_card_operation_id: { type: DataTypes.INTEGER, allowNull: false },
      material_id: { type: DataTypes.INTEGER, allowNull: false },
      required_quantity: { type: DataTypes.DECIMAL(18, 3), allowNull: false, defaultValue: 0 },
      completed_quantity: { type: DataTypes.DECIMAL(18, 3), allowNull: false, defaultValue: 0 },
      started_at: { type: DataTypes.DATE, allowNull: true },
      ended_at: { type: DataTypes.DATE, allowNull: true },
      total_minutes: { type: DataTypes.INTEGER, allowNull: false, defaultValue: 0 },
      created_by: { type: DataTypes.INTEGER, allowNull: true },
      updated_by: { type: DataTypes.INTEGER, allowNull: true },
    },
    {
      tableName: 'route_card_operation_component_tracking',
      indexes: [
        { unique: true, fields: ['route_card_operation_id', 'material_id'] },
        { fields: ['route_card_id'] },
      ],
    }
  );

  RouteCardOperationComponentTracking.associate = function (models) {
    RouteCardOperationComponentTracking.belongsTo(models.RouteCard, {
      foreignKey: 'route_card_id',
      as: 'routeCard',
    });
    RouteCardOperationComponentTracking.belongsTo(models.RouteCardOperation, {
      foreignKey: 'route_card_operation_id',
      as: 'operation',
    });
    RouteCardOperationComponentTracking.belongsTo(models.Material, {
      foreignKey: 'material_id',
      as: 'material',
    });
    RouteCardOperationComponentTracking.belongsTo(models.User, {
      foreignKey: 'created_by',
      as: 'createdByUser',
      constraints: false,
    });
    RouteCardOperationComponentTracking.belongsTo(models.User, {
      foreignKey: 'updated_by',
      as: 'updatedByUser',
      constraints: false,
    });
  };

  return RouteCardOperationComponentTracking;
};

