const { DataTypes } = require('sequelize');
const sequelize = require('../config/database');

const Message = sequelize.define('Message', {
  id: {
    type: DataTypes.UUID,
    defaultValue: DataTypes.UUIDV4,
    primaryKey: true
  },
  senderId: {
    type: DataTypes.UUID,
    allowNull: false,
    references: {
      model: 'Users',
      key: 'id'
    }
  },
  receiverId: {
    type: DataTypes.UUID,
    allowNull: false,
    references: {
      model: 'Users',
      key: 'id'
    }
  },
  content: {
    type: DataTypes.TEXT,
    allowNull: true
  },
  isRead: {
    type: DataTypes.BOOLEAN,
    defaultValue: false
  },
  imageFilename: {
    type: DataTypes.TEXT,
    allowNull: true
  }
}, {
  timestamps: true,
  validate: {
    contentOrImage() {
      const hasContent = this.content && this.content.trim().length > 0;
      if (!hasContent && !this.imageFilename) {
        throw new Error('Message must have content or an image');
      }
    }
  }
});

module.exports = Message;