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

sender_type: {
        type: DataTypes.ENUM,
      
      

        values: [

"user",


"agent",


"system",


"tool"

        ],

      },

content: {
        type: DataTypes.TEXT,
      
      

      },

format: {
        type: DataTypes.ENUM,
      
      

        values: [

"markdown",


"plain_text",


"html"

        ],

      },

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

      },

token_count: {
        type: DataTypes.INTEGER,
      
      

      },

sent_at: {
        type: DataTypes.DATE,
      
      

      },

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

  messages.associate = (db) => {

    db.messages.belongsToMany(db.message_attachments, {
      as: 'attachments',
      foreignKey: {
        name: 'messages_attachmentsId',
      },
      constraints: false,
      through: 'messagesAttachmentsMessage_attachments',
    });

    db.messages.belongsToMany(db.message_attachments, {
      as: 'attachments_filter',
      foreignKey: {
        name: 'messages_attachmentsId',
      },
      constraints: false,
      through: 'messagesAttachmentsMessage_attachments',
    });


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















    db.messages.hasMany(db.code_snippets, {
      as: 'code_snippets_message',
      foreignKey: {
          name: 'messageId',
      },
      constraints: false,
    });













//end loop



    db.messages.belongsTo(db.conversations, {
      as: 'conversation',
      foreignKey: {
        name: 'conversationId',
      },
      constraints: false,
    });

    db.messages.belongsTo(db.users, {
      as: 'sender_user',
      foreignKey: {
        name: 'sender_userId',
      },
      constraints: false,
    });

    db.messages.belongsTo(db.ai_agents, {
      as: 'sender_agent',
      foreignKey: {
        name: 'sender_agentId',
      },
      constraints: false,
    });

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




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

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



  return messages;
};


