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

name: {
        type: DataTypes.TEXT,
      
      

      },

url: {
        type: DataTypes.TEXT,
      
      

      },

status: {
        type: DataTypes.ENUM,
      
      

        values: [

"active",


"disabled"

        ],

      },

secret: {
        type: DataTypes.TEXT,
      
      

      },

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

  webhooks.associate = (db) => {

    db.webhooks.belongsToMany(db.webhook_subscriptions, {
      as: 'subscriptions',
      foreignKey: {
        name: 'webhooks_subscriptionsId',
      },
      constraints: false,
      through: 'webhooksSubscriptionsWebhook_subscriptions',
    });

    db.webhooks.belongsToMany(db.webhook_subscriptions, {
      as: 'subscriptions_filter',
      foreignKey: {
        name: 'webhooks_subscriptionsId',
      },
      constraints: false,
      through: 'webhooksSubscriptionsWebhook_subscriptions',
    });


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
















































    db.webhooks.hasMany(db.webhook_subscriptions, {
      as: 'webhook_subscriptions_webhook',
      foreignKey: {
          name: 'webhookId',
      },
      constraints: false,
    });


    db.webhooks.hasMany(db.webhook_deliveries, {
      as: 'webhook_deliveries_webhook',
      foreignKey: {
          name: 'webhookId',
      },
      constraints: false,
    });








//end loop



    db.webhooks.belongsTo(db.tenants, {
      as: 'tenant',
      foreignKey: {
        name: 'tenantId',
      },
      constraints: false,
    });

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




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

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



  return webhooks;
};


