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

audit_number: {
        type: DataTypes.TEXT,
      
      

      },

audit_type: {
        type: DataTypes.ENUM,
      
      

        values: [

"internal",


"supplier",


"notified_body",


"regulatory",


"certification",


"other"

        ],

      },

status: {
        type: DataTypes.ENUM,
      
      

        values: [

"planned",


"in_progress",


"report_issued",


"closed",


"cancelled"

        ],

      },

start_at: {
        type: DataTypes.DATE,
      
      

      },

end_at: {
        type: DataTypes.DATE,
      
      

      },

scope: {
        type: DataTypes.TEXT,
      
      

      },

summary: {
        type: DataTypes.TEXT,
      
      

      },

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

  audits.associate = (db) => {

    db.audits.belongsToMany(db.clauses, {
      as: 'mapped_clauses',
      foreignKey: {
        name: 'audits_mapped_clausesId',
      },
      constraints: false,
      through: 'auditsMapped_clausesClauses',
    });

    db.audits.belongsToMany(db.clauses, {
      as: 'mapped_clauses_filter',
      foreignKey: {
        name: 'audits_mapped_clausesId',
      },
      constraints: false,
      through: 'auditsMapped_clausesClauses',
    });


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





























    db.audits.hasMany(db.audit_findings, {
      as: 'audit_findings_audit',
      foreignKey: {
          name: 'auditId',
      },
      constraints: false,
    });






//end loop



    db.audits.belongsTo(db.users, {
      as: 'lead_auditor',
      foreignKey: {
        name: 'lead_auditorId',
      },
      constraints: false,
    });

    db.audits.belongsTo(db.suppliers, {
      as: 'supplier',
      foreignKey: {
        name: 'supplierId',
      },
      constraints: false,
    });



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


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

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



  return audits;
};


