"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.MongooseSupportMessageRepository = void 0;
const SupportMessageModel_js_1 = require("../models/SupportMessageModel.js");
class MongooseSupportMessageRepository {
    async findById(id) {
        const doc = await SupportMessageModel_js_1.SupportMessageModel.findById(id).lean();
        return doc ? this.mapDocument(doc) : null;
    }
    async findByTicketId(ticketId, limit = 100, before) {
        const query = { ticketId };
        if (before)
            query.createdAt = { $lt: before };
        const docs = await SupportMessageModel_js_1.SupportMessageModel.find(query)
            .sort({ createdAt: -1 })
            .limit(limit)
            .lean();
        return docs.map((doc) => this.mapDocument(doc)).reverse();
    }
    async findRecentByTicketIds(ticketIds, limit = 1) {
        const docs = await SupportMessageModel_js_1.SupportMessageModel.find({ ticketId: { $in: ticketIds } })
            .sort({ createdAt: -1 })
            .limit(limit)
            .lean();
        return docs.map((doc) => this.mapDocument(doc));
    }
    async create(input) {
        const doc = await SupportMessageModel_js_1.SupportMessageModel.create(input);
        return this.mapDocument(doc.toObject());
    }
    async markAsReadByAgent(messageIds) {
        const result = await SupportMessageModel_js_1.SupportMessageModel.updateMany({ _id: { $in: messageIds } }, { $set: { readByAgent: true } });
        return result.modifiedCount;
    }
    async markAsReadByUser(messageIds) {
        const result = await SupportMessageModel_js_1.SupportMessageModel.updateMany({ _id: { $in: messageIds } }, { $set: { readByUser: true } });
        return result.modifiedCount;
    }
    async search(query, ticketIds) {
        const mongoQuery = { $text: { $search: query } };
        if (ticketIds)
            mongoQuery.ticketId = { $in: ticketIds };
        const docs = await SupportMessageModel_js_1.SupportMessageModel.find(mongoQuery).sort({ createdAt: -1 }).lean();
        return docs.map((doc) => this.mapDocument(doc));
    }
    mapDocument(doc) {
        return {
            id: doc._id.toString(),
            ticketId: doc.ticketId,
            senderType: doc.senderType,
            senderId: doc.senderId,
            messageType: doc.messageType,
            text: doc.text,
            telegramMessageId: doc.telegramMessageId,
            telegramFileId: doc.telegramFileId,
            metadata: doc.metadata,
            internal: doc.internal,
            readByAgent: doc.readByAgent,
            readByUser: doc.readByUser,
            createdAt: doc.createdAt
        };
    }
}
exports.MongooseSupportMessageRepository = MongooseSupportMessageRepository;
