"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.renderServiceConnectionFailureMessage = renderServiceConnectionFailureMessage;
const catalog_1 = require("../../i18n/catalog");
function renderServiceConnectionFailureMessage(auth, target, input = {}, locale = catalog_1.DEFAULT_APP_LOCALE) {
    const lines = [
        (0, catalog_1.translate)(locale, "serviceConnection.failure.heading", {
            displayName: auth.displayName,
        }),
    ];
    const reason = formatFailureReason(input.reason);
    if (reason) {
        lines.push((0, catalog_1.translate)(locale, "serviceConnection.failure.reason", { reason }));
    }
    const instructions = auth.renderSetupInstructions(target, locale);
    if (instructions.length > 0) {
        lines.push((0, catalog_1.translate)(locale, "serviceConnection.failure.recommended"));
        lines.push(...instructions.map((instruction, index) => `${index + 1}. ${instruction}`));
    }
    if (input.retryCommand) {
        lines.push(`${instructions.length + 1}. ${(0, catalog_1.translate)(locale, "serviceConnection.failure.retryAgain", {
            retryCommand: input.retryCommand,
        })}`);
    }
    return lines.join("\n");
}
function formatFailureReason(reason) {
    const normalized = reason?.trim();
    if (!normalized) {
        return null;
    }
    if (normalized.includes("\n")) {
        return null;
    }
    for (const template of (0, catalog_1.translateAllLocales)("serviceConnection.need")) {
        if (matchesLocalizedTemplate(normalized, template)) {
            return null;
        }
    }
    for (const prefix of (0, catalog_1.translateAllLocales)("serviceConnection.failure.reason")) {
        const matchPrefix = prefix.replace("{{reason}}", "");
        if (normalized.startsWith(matchPrefix)) {
            return normalized.slice(matchPrefix.length).trim() || null;
        }
    }
    return normalized;
}
function matchesLocalizedTemplate(value, template) {
    const pattern = template
        .split(/(\{\{[^}]+\}\})/g)
        .filter((part) => part.length > 0)
        .map((part) => part.startsWith("{{") && part.endsWith("}}")
        ? "(.+?)"
        : escapeRegExp(part))
        .join("");
    return new RegExp(`^${pattern}$`).test(value);
}
function escapeRegExp(value) {
    return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
