const TARGET_FUNCTIONS = new Set(["cliAlert", "cliPrompt", "cliConfirm"]);

const plugin: Deno.lint.Plugin = {
  name: "must-await-calls",
  rules: {
    "must-await-calls": {
      create(context) {
        return {
          CallExpression(node) {
            if (
              node.callee.type !== "Identifier" ||
              !TARGET_FUNCTIONS.has(node.callee.name)
            ) return;

            const parent = node.parent;

            // Allow `await fetchData()`
            if (parent?.type === "AwaitExpression") return;

            // Allow `return fetchData()` or `return await fetchData()`
            if (parent?.type === "ReturnStatement") return;

            // Allow `fetchData().then(...)`
            if (
              parent?.type === "MemberExpression" &&
              parent.property.type === "Identifier" &&
              parent.property.name === "then"
            ) return;

            context.report({
              node,
              message:
                `Call to "${node.callee.name}" must be awaited, returned, or .then-chained.`,
              fix(fixer) {
                return fixer.insertTextBefore(node, "await ");
              },
            });
          },
        };
      },
    },
  },
};

export default plugin;
