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

severity: {
        type: DataTypes.ENUM,
      
      

        values: [

"minor",


"major",


"critical"

        ],

      },

status: {
        type: DataTypes.ENUM,
      
      

        values: [

"open",


"under_investigation",


"containment",


"capa_in_progress",


"closed",


"void"

        ],

      },

title: {
        type: DataTypes.TEXT,
      
      

      },

description: {
        type: DataTypes.TEXT,
      
      

      },

containment_action: {
        type: DataTypes.TEXT,
      
      

      },

detected_at: {
        type: DataTypes.DATE,
      
      

      },

closed_at: {
        type: DataTypes.DATE,
      
      

      },

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

  nonconformances.associate = (db) => {


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


























    db.nonconformances.hasMany(db.capa_actions, {
      as: 'capa_actions_nonconformance',
      foreignKey: {
          name: 'nonconformanceId',
      },
      constraints: false,
    });




//end loop



    db.nonconformances.belongsTo(db.quality_inspections, {
      as: 'quality_inspection',
      foreignKey: {
        name: 'quality_inspectionId',
      },
      constraints: false,
    });

    db.nonconformances.belongsTo(db.users, {
      as: 'reported_by',
      foreignKey: {
        name: 'reported_byId',
      },
      constraints: false,
    });

    db.nonconformances.belongsTo(db.items, {
      as: 'item',
      foreignKey: {
        name: 'itemId',
      },
      constraints: false,
    });

    db.nonconformances.belongsTo(db.inventory_lots, {
      as: 'lot',
      foreignKey: {
        name: 'lotId',
      },
      constraints: false,
    });

    db.nonconformances.belongsTo(db.organizations, {
      as: 'organizations',
      foreignKey: {
        name: 'organizationsId',
      },
      constraints: false,
    });



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


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

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



  return nonconformances;
};


