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

      type: {
        type: DataTypes.ENUM,

        values: [
          'HERO',

          'TEXT',

          'BUTTONS',

          'SOCIALS',

          'IMAGE',

          'MAP',

          'SPACER',
        ],
      },

      order_index: {
        type: DataTypes.INTEGER,
      },

      visible: {
        type: DataTypes.BOOLEAN,

        allowNull: false,
        defaultValue: false,
      },

      config: {
        type: DataTypes.TEXT,
      },

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

  blocks.associate = (db) => {
    /// loop through entities and it's fields, and if ref === current e[name] and create relation has many on parent entity

    db.blocks.hasMany(db.button_links, {
      as: 'button_links_block',
      foreignKey: {
        name: 'blockId',
      },
      constraints: false,
    });

    db.blocks.hasMany(db.social_links, {
      as: 'social_links_block',
      foreignKey: {
        name: 'blockId',
      },
      constraints: false,
    });

    //end loop

    db.blocks.belongsTo(db.profile_pages, {
      as: 'profile_page',
      foreignKey: {
        name: 'profile_pageId',
      },
      constraints: false,
    });

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

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

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

  return blocks;
};
