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

/**
 * Rule: component/require-arrow-function-nested
 * Enforces the use of arrow functions for function definitions inside components
 */
export default {
  meta: {
    type: 'suggestion',
    docs: {
      description: 'Enforces the use of arrow functions for function definitions inside components',
    },
    messages: {
      useArrowFunction:
        "Declare functions inside components using arrow function syntax (e.g., 'const {{ functionName }} = () => { ... }') instead of 'function {{ functionName }}() { ... }'.",
      useArrowFunctionForExpression:
        "Declare functions inside components using arrow function syntax (e.g., 'const {{ variableName }} = () => { ... }') instead of 'const {{ variableName }} = function() { ... }'.",
    },
  },
  create(context) {
    return {
      // Check for function declarations inside component definitions
      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 function declarations 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) {
          // Check for regular function declarations
          if (item.type === 'FunctionDeclaration' && !isHookName(item?.id?.name)) {
            context.report({
              node: item,
              messageId: 'useArrowFunction',
              data: {
                functionName: item.id.name,
              },
            });
          }

          // Check for function expressions assigned to variables
          if (item.type === 'VariableDeclaration') {
            const declaration = item.declarations[0];
            if (declaration?.init?.type === 'FunctionExpression' && !isHookName(declaration?.id?.name)) {
              context.report({
                node: item,
                messageId: 'useArrowFunctionForExpression',
                data: {
                  variableName: declaration.id.name,
                },
              });
            }
          }
        }
      },
    };
  },
};
