"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createSupportTicketController = createSupportTicketController;
function createSupportTicketController(ticketService, messageService, userService, noteService, orchestrator, logger) {
    return {
        list: async (req, res) => {
            try {
                const filters = {
                    status: parseArrayParam(req.query.status),
                    priority: parseArrayParam(req.query.priority),
                    category: req.query.category,
                    assignedAgent: req.query.assignedAgent,
                    userId: req.query.userId,
                    search: req.query.search,
                    page: req.query.page ? Number(req.query.page) : undefined,
                    limit: req.query.limit ? Number(req.query.limit) : undefined,
                    sort: req.query.sort ? JSON.parse(String(req.query.sort)) : undefined
                };
                const result = await ticketService.listTickets(filters);
                res.json({ success: true, data: result });
            }
            catch (error) {
                logger.error("Failed to list tickets.", { error: error instanceof Error ? error.message : String(error) });
                res.status(500).json({ success: false, error: "Failed to list tickets." });
            }
        },
        getById: async (req, res) => {
            try {
                const ticketId = String(req.params.id);
                const ticket = await ticketService.getById(ticketId);
                if (!ticket) {
                    res.status(404).json({ success: false, error: "Ticket not found." });
                    return;
                }
                const [messages, user, notes] = await Promise.all([
                    messageService.getMessagesByTicketId(ticketId, 200),
                    userService.getById(ticket.userId),
                    noteService.getNotesByTicketId(ticketId)
                ]);
                res.json({ success: true, data: { ticket, messages, user, notes } });
            }
            catch (error) {
                logger.error("Failed to get ticket.", { error: error instanceof Error ? error.message : String(error) });
                res.status(500).json({ success: false, error: "Failed to get ticket." });
            }
        },
        reply: async (req, res) => {
            try {
                const { text, messageType, telegramFileId, metadata } = req.body;
                const ticketId = String(req.params.id);
                const agentId = req.adminUser?.id ?? "admin";
                const result = await orchestrator.handleAgentReply({
                    ticketId,
                    agentId,
                    text,
                    messageType,
                    telegramFileId,
                    metadata
                });
                res.json({ success: true, data: result });
            }
            catch (error) {
                logger.error("Failed to reply to ticket.", { error: error instanceof Error ? error.message : String(error) });
                res.status(500).json({ success: false, error: "Failed to send reply." });
            }
        },
        assign: async (req, res) => {
            try {
                const { agentId } = req.body;
                const ticket = await orchestrator.assignTicketToAgent(String(req.params.id), agentId);
                if (!ticket) {
                    res.status(404).json({ success: false, error: "Ticket not found." });
                    return;
                }
                res.json({ success: true, data: ticket });
            }
            catch (error) {
                logger.error("Failed to assign ticket.", { error: error instanceof Error ? error.message : String(error) });
                res.status(500).json({ success: false, error: "Failed to assign ticket." });
            }
        },
        updateStatus: async (req, res) => {
            try {
                const { status } = req.body;
                const ticketId = String(req.params.id);
                const agentId = req.adminUser?.id ?? "admin";
                let ticket;
                if (status === "CLOSED") {
                    ticket = await orchestrator.closeTicket(ticketId, agentId);
                }
                else if (status === "RESOLVED") {
                    ticket = await orchestrator.resolveTicket(ticketId, agentId);
                }
                else {
                    ticket = await ticketService.updateStatus(ticketId, status, agentId);
                }
                if (!ticket) {
                    res.status(404).json({ success: false, error: "Ticket not found." });
                    return;
                }
                res.json({ success: true, data: ticket });
            }
            catch (error) {
                logger.error("Failed to update ticket status.", { error: error instanceof Error ? error.message : String(error) });
                res.status(500).json({ success: false, error: "Failed to update ticket status." });
            }
        },
        updatePriority: async (req, res) => {
            try {
                const { priority } = req.body;
                const ticket = await ticketService.updatePriority(String(req.params.id), priority);
                if (!ticket) {
                    res.status(404).json({ success: false, error: "Ticket not found." });
                    return;
                }
                res.json({ success: true, data: ticket });
            }
            catch (error) {
                logger.error("Failed to update ticket priority.", { error: error instanceof Error ? error.message : String(error) });
                res.status(500).json({ success: false, error: "Failed to update ticket priority." });
            }
        },
        markAsRead: async (req, res) => {
            try {
                await orchestrator.markMessagesAsReadByAgent(String(req.params.id));
                res.json({ success: true });
            }
            catch (error) {
                logger.error("Failed to mark messages as read.", { error: error instanceof Error ? error.message : String(error) });
                res.status(500).json({ success: false, error: "Failed to mark messages as read." });
            }
        }
    };
}
function parseArrayParam(value) {
    if (!value)
        return undefined;
    if (Array.isArray(value))
        return value.map(String);
    const str = String(value);
    if (str.includes(","))
        return str.split(",").map((s) => s.trim());
    return str;
}
