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 material_revisions = sequelize.define(
    'material_revisions',
    {
      id: {
        type: DataTypes.UUID,
        defaultValue: DataTypes.UUIDV4,
        primaryKey: true,
      },

revision_code: {
        type: DataTypes.TEXT,
      
      

      },

effective_from: {
        type: DataTypes.DATE,
      
      

      },

effective_to: {
        type: DataTypes.DATE,
      
      

      },

lifecycle_state: {
        type: DataTypes.ENUM,
      
      

        values: [

"draft",


"released",


"obsolete"

        ],

      },

change_summary: {
        type: DataTypes.TEXT,
      
      

      },

approved_at: {
        type: DataTypes.DATE,
      
      

      },

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

  material_revisions.associate = (db) => {


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













    db.material_revisions.hasMany(db.boms, {
      as: 'boms_revision',
      foreignKey: {
          name: 'revisionId',
      },
      constraints: false,
    });



    db.material_revisions.hasMany(db.routings, {
      as: 'routings_revision',
      foreignKey: {
          name: 'revisionId',
      },
      constraints: false,
    });














    db.material_revisions.hasMany(db.quality_standards, {
      as: 'quality_standards_revision',
      foreignKey: {
          name: 'revisionId',
      },
      constraints: false,
    });









//end loop



    db.material_revisions.belongsTo(db.materials, {
      as: 'material',
      foreignKey: {
        name: 'materialId',
      },
      constraints: false,
    });

    db.material_revisions.belongsTo(db.users, {
      as: 'approved_by_user',
      foreignKey: {
        name: 'approved_by_userId',
      },
      constraints: false,
    });



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


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

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



  return material_revisions;
};


