module.exports = {
    meta: {
        type: "problem",
        docs: {
            description: "Disallow the use of fetch in Node.js context",
            category: "Best Practices",
            recommended: true,
        },
        fixable: null,
        schema: [],
        messages: {
            noFetch: "Using fetch in Node.js can cause problems. Use ServerSideRendering fetch instead.",
        },
    },

    create(context) {
        let hasAllowedFetchImport = false;

        return {
            ImportDeclaration(node) {
                if (node.source.value === "node-fetch") {
                    context.report({
                        node,
                        messageId: "noFetch",
                    });
                    return;
                }

                if (node.source.value === "@insite/client-framework/ServerSideRendering") {
                    hasAllowedFetchImport = true;
                    return;
                }

                if (node.specifiers) {
                    node.specifiers.forEach(specifier => {
                        if (specifier.type === "ImportSpecifier" && specifier.imported.name === "fetch") {
                            context.report({
                                node: specifier,
                                messageId: "noFetch",
                            });
                        }
                    });
                }
            },

            CallExpression(node) {
                if (node.callee.type === "Identifier" && node.callee.name === "fetch") {
                    if (!hasAllowedFetchImport) {
                        context.report({
                            node,
                            messageId: "noFetch",
                        });
                    }
                }

                if (
                    node.callee.type === "Identifier" &&
                    node.callee.name === "require" &&
                    node.arguments.length > 0 &&
                    node.arguments[0].type === "Literal" &&
                    node.arguments[0].value === "node-fetch"
                ) {
                    context.report({
                        node,
                        messageId: "noFetch",
                    });
                }
            },

            MemberExpression(node) {
                if (
                    (node.object.name === "global" || node.object.name === "globalThis") &&
                    node.property.name === "fetch"
                ) {
                    context.report({
                        node,
                        messageId: "noFetch",
                    });
                }
            },
        };
    },
};
