module.exports = (sequelize, DataTypes) => {
  const ProductionQCComponentTracking = sequelize.define(
    'ProductionQCComponentTracking',
    {
      id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
      production_qc_id: { type: DataTypes.INTEGER, allowNull: false },
      company_id: { type: DataTypes.INTEGER, allowNull: false },
      plant_id: { type: DataTypes.INTEGER, allowNull: false },
      fiscal_year_id: { type: DataTypes.INTEGER, allowNull: false },
      customer_po_id: { type: DataTypes.INTEGER, allowNull: true },
      production_order_id: { type: DataTypes.INTEGER, allowNull: 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 },
      checked_qty: { type: DataTypes.DECIMAL(18, 3), allowNull: false, defaultValue: 0 },
      rework_qty: { type: DataTypes.DECIMAL(18, 3), allowNull: false, defaultValue: 0 },
      remarks: { type: DataTypes.TEXT, allowNull: true },
      created_by: { type: DataTypes.INTEGER, allowNull: true },
      updated_by: { type: DataTypes.INTEGER, allowNull: true },
    },
    {
      tableName: 'production_qc_component_tracking',
      indexes: [
        { unique: true, fields: ['production_qc_id', 'material_id'] },
        { fields: ['route_card_id', 'route_card_operation_id'] },
      ],
    }
  );

  ProductionQCComponentTracking.associate = function (models) {
    ProductionQCComponentTracking.belongsTo(models.ProductionQC, { foreignKey: 'production_qc_id', as: 'productionQC' });
    ProductionQCComponentTracking.belongsTo(models.RouteCard, { foreignKey: 'route_card_id', as: 'routeCard' });
    ProductionQCComponentTracking.belongsTo(models.RouteCardOperation, { foreignKey: 'route_card_operation_id', as: 'routeCardOperation' });
    ProductionQCComponentTracking.belongsTo(models.Material, { foreignKey: 'material_id', as: 'material' });
    ProductionQCComponentTracking.belongsTo(models.ProductionOrder, { foreignKey: 'production_order_id', as: 'productionOrder' });
    ProductionQCComponentTracking.belongsTo(models.CustomerPO, { foreignKey: 'customer_po_id', as: 'customerPO' });
    ProductionQCComponentTracking.belongsTo(models.User, { foreignKey: 'created_by', as: 'createdByUser', constraints: false });
    ProductionQCComponentTracking.belongsTo(models.User, { foreignKey: 'updated_by', as: 'updatedByUser', constraints: false });
  };

  return ProductionQCComponentTracking;
};

