"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SupportMessageService = void 0;
class SupportMessageService {
    messageRepository;
    ticketRepository;
    logger;
    constructor(messageRepository, ticketRepository, logger) {
        this.messageRepository = messageRepository;
        this.ticketRepository = ticketRepository;
        this.logger = logger;
    }
    async sendMessage(dto) {
        const ticket = await this.ticketRepository.findById(dto.ticketId);
        if (!ticket) {
            throw new Error(`Ticket not found: ${dto.ticketId}`);
        }
        const message = await this.messageRepository.create({
            ticketId: dto.ticketId,
            senderType: dto.senderType,
            senderId: dto.senderId,
            messageType: dto.messageType,
            text: dto.text,
            telegramMessageId: dto.telegramMessageId,
            telegramFileId: dto.telegramFileId,
            metadata: dto.metadata,
            internal: dto.internal ?? false
        });
        await this.ticketRepository.update(dto.ticketId, {
            lastMessage: dto.text ?? `[${dto.messageType}]`,
            lastActivity: new Date()
        });
        this.logger.info("Support message created.", {
            ticketId: dto.ticketId,
            senderType: dto.senderType,
            messageType: dto.messageType
        });
        return message;
    }
    async getMessagesByTicketId(ticketId, limit = 100, before) {
        return this.messageRepository.findByTicketId(ticketId, limit, before);
    }
    async markAsReadByAgent(ticketId) {
        const messages = await this.messageRepository.findByTicketId(ticketId, 1000);
        const unreadIds = messages.filter((m) => !m.readByAgent && m.senderType !== "AGENT").map((m) => m.id);
        return this.messageRepository.markAsReadByAgent(unreadIds);
    }
    async markAsReadByUser(ticketId) {
        const messages = await this.messageRepository.findByTicketId(ticketId, 1000);
        const unreadIds = messages.filter((m) => !m.readByUser && m.senderType === "AGENT").map((m) => m.id);
        return this.messageRepository.markAsReadByUser(unreadIds);
    }
    async searchMessages(query, ticketIds) {
        return this.messageRepository.search(query, ticketIds);
    }
}
exports.SupportMessageService = SupportMessageService;
