const config = require('../../config');
const providers = config.providers;
const crypto = require('crypto');
const bcrypt = require('bcrypt');
const moment = require('moment');

module.exports = function(sequelize, DataTypes) {
  const batches = sequelize.define(
    'batches',
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },

batch_number: {
        type: DataTypes.TEXT,
      
      

      },

status: {
        type: DataTypes.ENUM,
      
      

        values: [

"planned",


"in_process",


"quarantined",


"released",


"rejected",


"closed"

        ],

      },

manufacture_start_at: {
        type: DataTypes.DATE,
      
      

      },

manufacture_end_at: {
        type: DataTypes.DATE,
      
      

      },

quantity_planned: {
        type: DataTypes.DECIMAL,
      
      

      },

quantity_produced: {
        type: DataTypes.DECIMAL,
      
      

      },

quantity_released: {
        type: DataTypes.DECIMAL,
      
      

      },

notes: {
        type: DataTypes.TEXT,
      
      

      },

      importHash: {
        type: DataTypes.STRING(255),
        allowNull: true,
        unique: true,
      },
    },
    {
      timestamps: true,
      paranoid: true,
      freezeTableName: true,
    },
  );

  batches.associate = (db) => {


/// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity





















    db.batches.hasMany(db.certificates_of_analysis, {
      as: 'certificates_of_analysis_batch',
      foreignKey: {
          name: 'batchId',
      },
      constraints: false,
    });






    db.batches.hasMany(db.nonconformances, {
      as: 'nonconformances_batch',
      foreignKey: {
          name: 'batchId',
      },
      constraints: false,
    });









//end loop



    db.batches.belongsTo(db.products, {
      as: 'product',
      foreignKey: {
        name: 'productId',
      },
      constraints: false,
    });

    db.batches.belongsTo(db.documents, {
      as: 'bmr_document',
      foreignKey: {
        name: 'bmr_documentId',
      },
      constraints: false,
    });



    db.batches.hasMany(db.file, {
      as: 'batch_record_files',
      foreignKey: 'belongsToId',
      constraints: false,
      scope: {
        belongsTo: db.batches.getTableName(),
        belongsToColumn: 'batch_record_files',
      },
    });


    db.batches.belongsTo(db.users, {
      as: 'createdBy',
    });

    db.batches.belongsTo(db.users, {
      as: 'updatedBy',
    });
  };



  return batches;
};


