import mongoose, { Schema, Document } from 'mongoose';

export interface IMessage extends Document {
    organizationId: string;
    fromUserId: string; // externalId do remetente
    toUserId: string; // externalId do destinatário
    message: string;
    isRead: boolean;
    readAt?: Date;
    isArchived: boolean;
    isDeletedByRecipient: boolean;
    createdAt: Date;
    updatedAt: Date;
}

const MessageSchema: Schema = new Schema(
    {
        organizationId: {
            type: String,
            required: true,
            index: true,
        },
        fromUserId: {
            type: String,
            required: true,
            index: true,
        },
        toUserId: {
            type: String,
            required: true,
            index: true,
        },
        message: {
            type: String,
            required: true,
            maxlength: 255,
        },
        isRead: {
            type: Boolean,
            default: false,
        },
        readAt: {
            type: Date,
        },
        isArchived: {
            type: Boolean,
            default: false,
        },
        isDeletedByRecipient: {
            type: Boolean,
            default: false,
        }
    },
    {
        timestamps: true,
    }
);

// Compound index for efficient queries
MessageSchema.index({ toUserId: 1, isRead: 1 });
MessageSchema.index({ fromUserId: 1, toUserId: 1 });

export default mongoose.model<IMessage>('Message', MessageSchema);
