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,
      },

title: {
        type: DataTypes.TEXT,
      
      

      },

chat_status: {
        type: DataTypes.ENUM,
      
      

        values: [

"active",


"closed",


"archived"

        ],

      },

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

      },

started_at: {
        type: DataTypes.DATE,
      
      

      },

last_message_at: {
        type: DataTypes.DATE,
      
      

      },

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

  chats.associate = (db) => {

    db.chats.belongsToMany(db.chat_messages, {
      as: 'messages',
      foreignKey: {
        name: 'chats_messagesId',
      },
      constraints: false,
      through: 'chatsMessagesChat_messages',
    });

    db.chats.belongsToMany(db.chat_messages, {
      as: 'messages_filter',
      foreignKey: {
        name: 'chats_messagesId',
      },
      constraints: false,
      through: 'chatsMessagesChat_messages',
    });


/// 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_messages, {
      as: 'chat_messages_chat',
      foreignKey: {
          name: 'chatId',
      },
      constraints: false,
    });


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














//end loop



    db.chats.belongsTo(db.workspaces, {
      as: 'workspace',
      foreignKey: {
        name: 'workspaceId',
      },
      constraints: false,
    });

    db.chats.belongsTo(db.users, {
      as: 'user',
      foreignKey: {
        name: 'userId',
      },
      constraints: false,
    });

    db.chats.belongsTo(db.llm_models, {
      as: 'model',
      foreignKey: {
        name: 'modelId',
      },
      constraints: false,
    });

    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;
};


