import path from 'path';
import { isHookName } from '../utils/index.js';

/**
 * Rule: component/require-usecallback-for-function
 * Enforces the use of useCallback for functions defined inside components
 */
export default {
  meta: {
    type: 'suggestion',
    docs: {
      description: 'Enforces the use of useCallback for functions defined inside components',
    },
    messages: {
      wrapWithUseCallback:
        "Arrow function '{{ functionName }}' defined inside component '{{ componentName }}' should be wrapped in useCallback to ensure reference stability.",
    },
  },
  create(context) {
    return {
      // Check for functions inside components
      VariableDeclarator(node) {
        const filename = context.getFilename();
        const componentName = path.basename(filename, '.tsx');

        // Skip if not the main component variable
        if (node.id?.name !== componentName) {
          return;
        }

        // Find arrow functions in the component body
        const componentBody = node?.init?.body?.body;
        if (!componentBody || !Array.isArray(componentBody)) {
          return;
        }

        // Check each statement in the component body
        for (const item of componentBody) {
          // Skip if not a variable declaration
          if (item.type !== 'VariableDeclaration' || !item.declarations || item.declarations.length === 0) {
            continue;
          }

          const declaration = item.declarations[0];

          // Check if it's an arrow function not wrapped in useCallback
          if (
            declaration?.init?.type === 'ArrowFunctionExpression' &&
            !isHookName(declaration?.id?.name) &&
            declaration?.init?.callee?.name !== 'useCallback'
          ) {
            context.report({
              node: item,
              messageId: 'wrapWithUseCallback',
              data: {
                functionName: declaration.id.name,
                componentName,
              },
            });
          }
        }
      },
    };
  },
};
