"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.testEndHook = exports.testSystemInfoHook = exports.errorInStepHook = void 0;
const utils_1 = require("./utils");
async function errorInStepHook(testContext, fnName, proxyContext, rootPage, args, instrumentedFunctionResult) {
    if (!instrumentedFunctionResult.success) {
        testContext.addStepMetadata({
            stepError: unknownErrorToOurRepresentation(instrumentedFunctionResult.error),
        });
    }
}
exports.errorInStepHook = errorInStepHook;
async function testSystemInfoHook(testContext, proxyContext, rootPage) {
    const systemInfo = await utils_1.getSystemInfoForPage(rootPage);
    testContext.addTestMetadata({
        systemInfo,
    });
}
exports.testSystemInfoHook = testSystemInfoHook;
function unknownErrorToOurRepresentation(error) {
    var _a, _b, _c;
    if (error instanceof Error) {
        return {
            name: error.name,
            message: error.message,
            stack: error.stack,
        };
    }
    if (typeof error === 'object' && error !== null && 'message' in error) {
        const crossRealmError = error;
        return {
            name: (_a = crossRealmError === null || crossRealmError === void 0 ? void 0 : crossRealmError.name) !== null && _a !== void 0 ? _a : '',
            message: (_b = crossRealmError === null || crossRealmError === void 0 ? void 0 : crossRealmError.message) !== null && _b !== void 0 ? _b : '',
            stack: (_c = crossRealmError === null || crossRealmError === void 0 ? void 0 : crossRealmError.stack) !== null && _c !== void 0 ? _c : '',
        };
    }
    return {
        name: 'non serializable error?',
        message: 'non serializabsle error',
    };
}
async function testEndHook(testContext, testEndStatus) {
    var _a;
    const error = testEndStatus.success ? undefined : unknownErrorToOurRepresentation(testEndStatus.error);
    testContext.addTestMetadata({
        testEndStatus: {
            success: testEndStatus.success,
            error,
        },
    });
    if (!testEndStatus.success) {
        if ((_a = testContext.currentStep) === null || _a === void 0 ? void 0 : _a.stepError) {
            const metadata = {
                stepError: error,
            };
            testContext.addStepMetadata(metadata);
        }
        else {
            testContext.stepStarted();
            const metadata = {
                stepError: error,
                fnName: 'Assertion Error',
                rect: { error: 'Assertion Error' },
                screenshot: null,
                text: error && error.message,
            };
            testContext.addStepMetadata(metadata);
            await testContext.stepEnded();
        }
    }
}
exports.testEndHook = testEndHook;
