"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.loadSupportMethods = loadSupportMethods;
var axios_1 = require("axios");
var simpl_schema_1 = require("simpl-schema");
var SUPPORT_INTERNAL_MESSAGE_PATTERN = /\b(codex|openai|ai dashboard|ai assistant|workflow update|build plan|pull request|confidence gate|dependency follow-up|thread key|workspace cleanup|support automation|auto-?improve(?: loop)?|autoloop|support codex manager)\b/i;
var SUPPORT_INTERNAL_SOURCE_PATTERN = /\b(support_automation|codex|openai|ai(?:[_ -]?assistant|[_ -]?dashboard)?)\b/i;
function loadSupportMethods(methodManager) {
    methodManager.methods({
        supportCreateBillingUser: {
            check: new simpl_schema_1.default({
                user: {
                    type: Object,
                    blackbox: true
                }
            }),
            bypassLogs: true,
            function: function (user) {
                return __awaiter(this, void 0, void 0, function () {
                    var body, _a;
                    return __generator(this, function (_b) {
                        switch (_b.label) {
                            case 0:
                                _b.trys.push([0, 2, , 3]);
                                return [4 /*yield*/, axios_1.default.post('https://backend.resolveio.com/api/support/billing-user', user)];
                            case 1:
                                body = _b.sent();
                                return [2 /*return*/, body.data.result];
                            case 2:
                                _a = _b.sent();
                                return [2 /*return*/, false];
                            case 3: return [2 /*return*/];
                        }
                    });
                });
            }
        },
        supportGetSupportTicketWithId: {
            check: new simpl_schema_1.default({
                id_support_ticket: {
                    type: String
                }
            }),
            function: function (id_support_ticket) {
                return __awaiter(this, void 0, void 0, function () {
                    var body, error_1;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                _a.trys.push([0, 2, , 3]);
                                return [4 /*yield*/, axios_1.default.post('https://backend.resolveio.com/api/support/supportTicketWithId', { id_support_ticket: id_support_ticket })];
                            case 1:
                                body = _a.sent();
                                return [2 /*return*/, sanitizeSupportTicketForClientView(body.data.result)];
                            case 2:
                                error_1 = _a.sent();
                                error_1.message = "Error in Support Get Support Ticket With Id: ".concat(error_1.message);
                                throw error_1;
                            case 3: return [2 /*return*/];
                        }
                    });
                });
            }
        },
        supportInsertSupportTicket: {
            skipValidation: true,
            function: function (supportTicket) {
                return __awaiter(this, void 0, void 0, function () {
                    var safePayload, body, error_2;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                _a.trys.push([0, 2, , 3]);
                                safePayload = sanitizeSupportTicketCreatePayload(supportTicket);
                                return [4 /*yield*/, axios_1.default.post('https://backend.resolveio.com/api/support/supportInsertTicket', safePayload)];
                            case 1:
                                body = _a.sent();
                                return [2 /*return*/, body.data.result];
                            case 2:
                                error_2 = _a.sent();
                                error_2.message = "Error in Support Insert Support Ticket: ".concat(error_2.message);
                                throw error_2;
                            case 3: return [2 /*return*/];
                        }
                    });
                });
            }
        },
        supportUpdateSupportTicket: {
            skipValidation: true,
            function: function (supportTicket) {
                return __awaiter(this, void 0, void 0, function () {
                    var safePayload, body, error_3;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                _a.trys.push([0, 2, , 3]);
                                safePayload = sanitizeSupportTicketUpdatePayload(supportTicket);
                                return [4 /*yield*/, axios_1.default.post('https://backend.resolveio.com/api/support/supportUpdateTicket', safePayload)];
                            case 1:
                                body = _a.sent();
                                return [2 /*return*/, body.data.result];
                            case 2:
                                error_3 = _a.sent();
                                error_3.message = "Error in Support Update Support Ticket: ".concat(error_3.message);
                                throw error_3;
                            case 3: return [2 /*return*/];
                        }
                    });
                });
            }
        },
        supportticketsWithOptions: {
            check: new simpl_schema_1.default({
                options: {
                    type: Object
                },
                'options.limit': {
                    type: Number
                },
                'options.skip': {
                    type: Number
                },
                'options.sort': {
                    type: Object,
                    blackbox: true
                },
                'options.fields': {
                    type: Object,
                    blackbox: true
                },
                searchString: {
                    type: String
                },
                filters: {
                    type: Array
                },
                'filters.$': {
                    type: Object,
                    blackbox: true
                }
            }),
            function: function (options, searchString, filters) {
                return __awaiter(this, void 0, void 0, function () {
                    var safeFilters, body, results, error_4;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                _a.trys.push([0, 2, , 3]);
                                safeFilters = sanitizeSupportTicketFiltersForBackend(filters);
                                return [4 /*yield*/, axios_1.default.post('https://backend.resolveio.com/api/support/supportticketsWithOptions', [options, searchString, safeFilters])];
                            case 1:
                                body = _a.sent();
                                results = Array.isArray(body.data.result) ? body.data.result : [];
                                return [2 /*return*/, results.map(function (ticket) { return sanitizeSupportTicketForClientView(ticket); })];
                            case 2:
                                error_4 = _a.sent();
                                error_4.message = "Error in Support Tickets With Options: ".concat(error_4.message);
                                throw error_4;
                            case 3: return [2 /*return*/];
                        }
                    });
                });
            }
        },
        supportticketCount: {
            check: new simpl_schema_1.default({
                searchString: {
                    type: String
                },
                filters: {
                    type: Array
                },
                'filters.$': {
                    type: Object,
                    blackbox: true
                }
            }),
            function: function (searchString, filters) {
                return __awaiter(this, void 0, void 0, function () {
                    var safeFilters, body, error_5;
                    return __generator(this, function (_a) {
                        switch (_a.label) {
                            case 0:
                                _a.trys.push([0, 2, , 3]);
                                safeFilters = sanitizeSupportTicketFiltersForBackend(filters);
                                return [4 /*yield*/, axios_1.default.post('https://backend.resolveio.com/api/support/supportCountTickets', [searchString, safeFilters])];
                            case 1:
                                body = _a.sent();
                                return [2 /*return*/, body.data.result];
                            case 2:
                                error_5 = _a.sent();
                                error_5.message = "Error in Support Ticket Count: ".concat(error_5.message);
                                throw error_5;
                            case 3: return [2 /*return*/];
                        }
                    });
                });
            }
        }
    });
}
function isInternalSupportMessage(message) {
    if (!message || typeof message !== 'object') {
        return false;
    }
    if (message.internal === true) {
        return true;
    }
    var visibility = String(message.visibility || '').trim().toLowerCase();
    if (visibility === 'internal') {
        return true;
    }
    var badge = String(message.badge || '').trim().toLowerCase();
    if (badge.includes('internal')) {
        return true;
    }
    var source = String(message.source || '').trim();
    if (source && SUPPORT_INTERNAL_SOURCE_PATTERN.test(source)) {
        return true;
    }
    var text = [
        String(message.type || ''),
        String(message.user || ''),
        String(message.message || '')
    ].join(' ');
    return SUPPORT_INTERNAL_MESSAGE_PATTERN.test(text);
}
function stripSupportMessageInternalMetadata(message) {
    var next = __assign({}, (message || {}));
    delete next.internal;
    delete next.visibility;
    delete next.badge;
    delete next.source;
    return next;
}
function buildSupportTicketDetailPath(ticket) {
    var ticketId = String((ticket === null || ticket === void 0 ? void 0 : ticket._id) || '').trim();
    if (!ticketId) {
        return '/support-ticket/detail';
    }
    return "/support-ticket/detail/".concat(ticketId);
}
function sanitizeSupportTicketForClientView(ticket) {
    if (!ticket || typeof ticket !== 'object') {
        return ticket;
    }
    var next = __assign({}, ticket);
    next.status = normalizeSupportTicketStatusForClient(ticket.status);
    next.messages = Array.isArray(ticket.messages)
        ? ticket.messages
            .filter(function (message) { return !isInternalSupportMessage(message); })
            .map(function (message) { return stripSupportMessageInternalMetadata(message); })
        : [];
    next.url_ticket = String(ticket.url_ticket || '').trim() || buildSupportTicketDetailPath(ticket);
    next.notes = [];
    delete next.automation;
    delete next.ai_recommendations;
    delete next.source;
    return next;
}
function sanitizeSupportTicketCreatePayload(ticket) {
    if (!ticket || typeof ticket !== 'object') {
        return ticket;
    }
    var next = __assign({}, ticket);
    next.status = normalizeSupportTicketStatusForBackend(ticket.status);
    next.files = normalizeSupportTicketFileIds(ticket.files);
    next.messages = Array.isArray(ticket.messages)
        ? ticket.messages
            .filter(function (message) { return !isInternalSupportMessage(message); })
            .map(function (message) { return stripSupportMessageInternalMetadata(message); })
        : [];
    delete next.url_ticket;
    return next;
}
function sanitizeSupportTicketUpdatePayload(ticket) {
    if (!ticket || typeof ticket !== 'object') {
        return ticket;
    }
    var next = __assign({}, ticket);
    next.status = normalizeSupportTicketStatusForBackend(ticket.status);
    next.files = normalizeSupportTicketFileIds(ticket.files);
    next.messages = Array.isArray(ticket.messages)
        ? ticket.messages
            .filter(function (message) { return !isInternalSupportMessage(message); })
            .map(function (message) { return stripSupportMessageInternalMetadata(message); })
        : [];
    next.notes = Array.isArray(ticket.notes)
        ? ticket.notes.filter(function (note) { return !!note && typeof note === 'object'; })
        : [];
    delete next.automation;
    delete next.ai_recommendations;
    delete next.source;
    delete next.url_ticket;
    return next;
}
function normalizeSupportTicketFileIds(files) {
    if (!Array.isArray(files)) {
        return [];
    }
    return files
        .map(function (file) {
        if (typeof file === 'string') {
            return file.trim();
        }
        if (file && typeof file === 'object') {
            return String(file._id || file.id_file || file.id || '').trim();
        }
        return '';
    })
        .filter(function (id) { return !!id; });
}
function normalizeSupportTicketStatusForClient(status) {
    var value = String(status || '').trim().toLowerCase();
    if (value === 'opened' || value === 'active') {
        return 'Active';
    }
    if (value === 'review') {
        return 'Review';
    }
    if (value === 'resolved' || value === 'closed') {
        return 'Closed';
    }
    return String(status || '').trim();
}
function normalizeSupportTicketStatusForBackend(status) {
    var value = String(status || '').trim().toLowerCase();
    if (value === 'active' || value === 'opened') {
        return 'Opened';
    }
    if (value === 'review') {
        return 'Review';
    }
    if (value === 'resolved' || value === 'closed') {
        return 'Closed';
    }
    return String(status || '').trim();
}
function sanitizeSupportTicketFiltersForBackend(filters) {
    if (!Array.isArray(filters)) {
        return [];
    }
    return filters.map(function (filter) { return sanitizeSupportTicketFilterForBackend(filter); });
}
function sanitizeSupportTicketFilterForBackend(filter) {
    if (!filter || typeof filter !== 'object') {
        return filter;
    }
    var next = __assign({}, filter);
    if (String(filter.prop || '').trim() !== 'status') {
        return next;
    }
    next.data = normalizeSupportTicketFilterDataForBackend(filter.data);
    return next;
}
function normalizeSupportTicketFilterDataForBackend(value) {
    if (typeof value === 'string') {
        return normalizeSupportTicketStatusForBackend(value);
    }
    if (Array.isArray(value)) {
        return value.map(function (item) { return normalizeSupportTicketFilterDataForBackend(item); });
    }
    if (!value || typeof value !== 'object') {
        return value;
    }
    var next = __assign({}, value);
    if (typeof next.$eq === 'string') {
        next.$eq = normalizeSupportTicketStatusForBackend(next.$eq);
    }
    if (typeof next.$ne === 'string') {
        next.$ne = normalizeSupportTicketStatusForBackend(next.$ne);
    }
    if (Array.isArray(next.$in)) {
        next.$in = next.$in.map(function (entry) { return normalizeSupportTicketFilterDataForBackend(entry); });
    }
    if (Array.isArray(next.$nin)) {
        next.$nin = next.$nin.map(function (entry) { return normalizeSupportTicketFilterDataForBackend(entry); });
    }
    return next;
}

//# sourceMappingURL=support.js.map
