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

      name: {
        type: DataTypes.TEXT,
      },

      org: {
        type: DataTypes.TEXT,
      },

      email: {
        type: DataTypes.TEXT,
      },

      role: {
        type: DataTypes.ENUM,

        values: ['admin', 'user'],
      },

      status: {
        type: DataTypes.ENUM,

        values: ['active', 'pending', 'suspended'],
      },

      last_login: {
        type: DataTypes.DATE,
      },

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

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

    db.subscribers.hasMany(db.patient_profiles, {
      as: 'patient_profiles_subscriber',
      foreignKey: {
        name: 'subscriberId',
      },
      constraints: false,
    });

    db.subscribers.hasMany(db.subscriber_activities, {
      as: 'subscriber_activities_subscriber',
      foreignKey: {
        name: 'subscriberId',
      },
      constraints: false,
    });

    db.subscribers.hasMany(db.subscriber_roles, {
      as: 'subscriber_roles_subscriber',
      foreignKey: {
        name: 'subscriberId',
      },
      constraints: false,
    });

    //end loop

    db.subscribers.belongsTo(db.organizations, {
      as: 'organization',
      foreignKey: {
        name: 'organizationId',
      },
      constraints: false,
    });

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

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

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

  return subscribers;
};
