import { DataTypes, Model, Optional } from 'sequelize';
import { sequelize } from '../config/database';

interface ChatRoomMemberAttributes {
  id: number;
  room_id: number;
  user_id: string;
  role: 'admin' | 'member';
  joined_at?: Date;
  createdAt?: Date;
  updatedAt?: Date;
}

interface ChatRoomMemberCreationAttributes extends Optional<ChatRoomMemberAttributes, 'id' | 'joined_at' | 'createdAt' | 'updatedAt'> {}

class ChatRoomMember extends Model<ChatRoomMemberAttributes, ChatRoomMemberCreationAttributes> implements ChatRoomMemberAttributes {
  public id!: number;
  public room_id!: number;
  public user_id!: string;
  public role!: 'admin' | 'member';
  public joined_at?: Date;
  public readonly createdAt!: Date;
  public readonly updatedAt!: Date;
}

ChatRoomMember.init(
  {
    id: {
      type: DataTypes.INTEGER.UNSIGNED,
      autoIncrement: true,
      primaryKey: true,
    },
    room_id: {
      type: DataTypes.INTEGER.UNSIGNED,
      allowNull: false,
      references: {
        model: 'chat_rooms',
        key: 'id',
      },
    },
    user_id: {
      type: DataTypes.STRING(50),
      allowNull: false,
      references: {
        model: 'users',
        key: 'user_id',
      },
    },
    role: {
      type: DataTypes.ENUM('admin', 'member'),
      allowNull: false,
      defaultValue: 'member',
    },
    joined_at: {
      type: DataTypes.DATE,
      allowNull: true,
      defaultValue: DataTypes.NOW,
    },
  },
  {
    sequelize,
    tableName: 'chat_room_members',
    timestamps: true,
    indexes: [
      {
        unique: true,
        fields: ['room_id', 'user_id'],
      },
    ],
  }
);

// Relationships will be defined in models/index.ts to avoid circular dependencies

export default ChatRoomMember;
