import { Rule } from "eslint";

const plugin: {
  meta: {
    name: string;
    version: string;
  };
  rules: Record<string, Rule.RuleModule>;
} = {
  meta: {
    name: "eslint-plugin-structured-todo",
    version: "0.2.2",
  },
  rules: {
    "no-unstructured-todo": {
      meta: {
        type: "problem",
        docs: {
          description: "Disallow unstructured TODO comments",
          recommended: true,
        },
        schema: [],
        messages: {
          unstructuredTodo:
            "Use TODO format '// TODO(created=2025-09-17, author=ian): message'. 'created' is mandatory",
        },
      },
      create(context: Rule.RuleContext): Rule.RuleListener {
        const hasTodo = (string: string) => string.includes("TODO");

        const hasCorrectTodo = (todoString: string) => {
          const parenthesis = todoString.match(/(?:\()[^\(\)]*?(?:\))/);
          if (!parenthesis || !parenthesis[0]) return false;
          const hasCorrectCreated = parenthesis[0].match(
            /created=\d{4}-\d{2}-\d{2}/
          );
          return Boolean(hasCorrectCreated);
        };

        return {
          Program(): void {
            const sourceCode = context.getSourceCode();
            const comments = sourceCode.getAllComments();

            comments.forEach((comment) => {
              if (
                comment.type === "Line" &&
                hasTodo(comment.value) &&
                !hasCorrectTodo(comment.value)
              ) {
                context.report({
                  // @ts-ignore
                  node: comment,
                  messageId: "unstructuredTodo",
                });
              }
            });
          },
        };
      },
    },
  },
};

// for ESM
export default plugin;
