import { getComputedArgsString, isComputedPropertyInfo, isTemplatePropertyInfo, } from "@superblocksteam/library-shared";
import { getFunctionBodyThisExpressionData, parseExpression } from "../util.js";
function isValidJSXExpression(value) {
    try {
        return parseExpression(`<div test={${value}} />`) !== null;
    }
    catch (_e) {
        return false;
    }
}
const transformers = {
    oneLineArrow: (value, argsString) => value.startsWith("{")
        ? `(${argsString}) => (${value})`
        : `(${argsString}) => ${value}`,
    multiLineArrow: (value, argsString) => `(${argsString}) => {
    ${value}
  }`,
    traditional: (value, argsString) => `function (this: any${argsString ? `, ${argsString}` : ""}) {
    ${value}
  }`,
    computed: (value) => `computed(${value})`,
};
function findFirstValidExpression(testCases) {
    return testCases.find(isValidJSXExpression);
}
export function toCodeComputed(value, info) {
    // normal course of operations this does not happen, but we should be extra careful
    if (value == null) {
        value = "";
    }
    let argsString = "";
    if (isComputedPropertyInfo(info) || isTemplatePropertyInfo(info)) {
        argsString = getComputedArgsString(info.args);
    }
    // We should short circuit behavior if we contain a `this` reference in the function body
    const { hasThisReference, hasReturnStatement } = getFunctionBodyThisExpressionData(value);
    if (hasThisReference) {
        if (!hasReturnStatement) {
            return transformers.computed(transformers.traditional(`return ${value}`, argsString));
        }
        return transformers.computed(transformers.traditional(value, argsString));
    }
    const computedTestCases = [
        transformers.oneLineArrow(value, argsString),
        transformers.multiLineArrow(value, argsString),
        transformers.traditional(value, argsString),
    ];
    const validComputedExpression = findFirstValidExpression(computedTestCases);
    if (validComputedExpression) {
        return transformers.computed(validComputedExpression);
    }
    return transformers.computed(transformers.multiLineArrow(value, argsString));
}
//# sourceMappingURL=to-code-computed.js.map