"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isNetworkError = isNetworkError;
exports.handleCommandFailure = handleCommandFailure;
const types_1 = require("@playdrop/types");
const http_1 = require("./http");
const messages_1 = require("./messages");
function isNetworkError(error) {
    if (!error || typeof error !== 'object') {
        return false;
    }
    const candidate = error;
    if (candidate instanceof TypeError) {
        return true;
    }
    const code = typeof candidate.code === 'string' ? candidate.code : undefined;
    if (code === 'ECONNREFUSED' || code === 'ENOTFOUND') {
        return true;
    }
    const cause = candidate.cause;
    if (cause && typeof cause === 'object' && typeof cause.code === 'string') {
        const nestedCode = cause.code;
        return nestedCode === 'ECONNREFUSED' || nestedCode === 'ENOTFOUND';
    }
    return false;
}
function handleCommandFailure(error, command, context, options = {}) {
    if (error instanceof http_1.CLIUnsupportedClientError) {
        return true;
    }
    if (error instanceof types_1.UnsupportedClientError) {
        (0, http_1.handleUnsupportedError)(error, context);
        return true;
    }
    if (error instanceof types_1.ApiError) {
        const apiMessage = options.apiMessage
            ? options.apiMessage(error)
            : {
                problem: `${context} failed with status ${error.status}.`,
                suggestions: ['Retry in a moment.'],
            };
        (0, messages_1.printErrorWithHelp)(apiMessage.problem, apiMessage.suggestions ?? [], { command });
        process.exitCode = 1;
        return true;
    }
    if (isNetworkError(error)) {
        (0, messages_1.printNetworkIssue)(options.networkMessage || 'Could not reach the Playdrop API.', command);
        process.exitCode = 1;
        return true;
    }
    return false;
}
