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

capa_number: {
        type: DataTypes.TEXT,
      
      

      },

source: {
        type: DataTypes.ENUM,
      
      

        values: [

"complaint",


"audit",


"nonconformance",


"process_monitoring",


"supplier",


"management_review",


"risk_management",


"other"

        ],

      },

status: {
        type: DataTypes.ENUM,
      
      

        values: [

"draft",


"open",


"containment",


"investigation",


"action_plan",


"implementation",


"effectiveness_check",


"closed",


"rejected"

        ],

      },

problem_statement: {
        type: DataTypes.TEXT,
      
      

      },

root_cause: {
        type: DataTypes.TEXT,
      
      

      },

corrective_actions: {
        type: DataTypes.TEXT,
      
      

      },

preventive_actions: {
        type: DataTypes.TEXT,
      
      

      },

opened_at: {
        type: DataTypes.DATE,
      
      

      },

due_at: {
        type: DataTypes.DATE,
      
      

      },

closed_at: {
        type: DataTypes.DATE,
      
      

      },

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

  capas.associate = (db) => {


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





























    db.capas.hasMany(db.audit_findings, {
      as: 'audit_findings_related_capa',
      foreignKey: {
          name: 'related_capaId',
      },
      constraints: false,
    });






//end loop



    db.capas.belongsTo(db.users, {
      as: 'owner',
      foreignKey: {
        name: 'ownerId',
      },
      constraints: false,
    });

    db.capas.belongsTo(db.documents, {
      as: 'related_document',
      foreignKey: {
        name: 'related_documentId',
      },
      constraints: false,
    });



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


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

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



  return capas;
};


