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

chat_type: {
        type: DataTypes.ENUM,
      
      

        values: [

"direct",


"group",


"business_thread"

        ],

      },

chat_title: {
        type: DataTypes.TEXT,
      
      

      },

last_message_at: {
        type: DataTypes.DATE,
      
      

      },

is_encrypted: {
        type: DataTypes.BOOLEAN,
      
        allowNull: false,
        defaultValue: false,
      
      

      },

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

  chats.associate = (db) => {

    db.chats.belongsToMany(db.chat_participants, {
      as: 'participants',
      foreignKey: {
        name: 'chats_participantsId',
      },
      constraints: false,
      through: 'chatsParticipantsChat_participants',
    });

    db.chats.belongsToMany(db.chat_participants, {
      as: 'participants_filter',
      foreignKey: {
        name: 'chats_participantsId',
      },
      constraints: false,
      through: 'chatsParticipantsChat_participants',
    });


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











    db.chats.hasMany(db.chat_participants, {
      as: 'chat_participants_chat',
      foreignKey: {
          name: 'chatId',
      },
      constraints: false,
    });


    db.chats.hasMany(db.messages, {
      as: 'messages_chat',
      foreignKey: {
          name: 'chatId',
      },
      constraints: false,
    });

































//end loop



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




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

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



  return chats;
};


