import { parseManifestUseCases } from "./_manifest-ast.js";
import { manifestPathForFeature } from "./_manifest-source.js";
import { repoRootSchema } from "./_rule-schema.js";
import { resolveRuleContext } from "./_rule-context.js";

/** @type {import("eslint").Rule.RuleModule} */
export default {
  meta: {
    type: "problem",
    docs: {
      description:
        'bus.publish("X") inside a use-case factory must declare X in manifest.useCases[name].publishes.',
    },
    schema: repoRootSchema,
    messages: {
      undeclared:
        '{{useCase}} calls bus.publish("{{event}}") but {{event}} is not declared in manifest.useCases.{{useCase}}.publishes. Add it to the manifest or remove the call.',
    },
  },
  create(context) {
    const rc = resolveRuleContext(context);
    if (!rc) return {};
    const { useCaseName, featureRoot } = rc;
    const manifest = parseManifestUseCases(manifestPathForFeature(featureRoot));
    if (!manifest || !manifest[useCaseName]) return {};
    const declared = new Set(manifest[useCaseName].publishes);
    return {
      CallExpression(node) {
        if (
          node.callee.type === "MemberExpression" &&
          node.callee.object.type === "Identifier" &&
          node.callee.object.name === "bus" &&
          node.callee.property.type === "Identifier" &&
          node.callee.property.name === "publish" &&
          node.arguments.length > 0 &&
          node.arguments[0].type === "Literal" &&
          typeof node.arguments[0].value === "string"
        ) {
          const event = node.arguments[0].value;
          if (!declared.has(event)) {
            context.report({
              node,
              messageId: "undeclared",
              data: { event, useCase: useCaseName },
            });
          }
        }
      },
    };
  },
};
