import path from 'path';

/**
 * Rule: naming-convention/function-matches-filename
 * Ensures that function names match their filenames
 */
export default {
  meta: {
    type: 'suggestion',
    docs: {
      description: 'Ensures that function names match their filenames',
    },
  },
  create(context) {
    const { filename } = context;
    const basename = path.basename(filename, '.ts');
    let variableName = null;
    if (basename === 'index') {
      return {};
    }
    return {
      ArrowFunctionExpression(node) {
        if (node?.id?.name === basename) {
          variableName = node?.id?.name;
        }
      },
      FunctionDeclaration(node) {
        if (node.id && node.id.name === basename) {
          variableName = node.id.name;
        }
      },
      VariableDeclaration(node) {
        if (node.declarations) {
          for (const declaration of node.declarations) {
            if (declaration.id && declaration.id.name === basename) {
              variableName = declaration.id.name;
            }
          }
        }
      },
      'Program:exit'() {
        if (variableName !== basename) {
          context.report({
            message: `File name "${basename}" should have the function or variable name "${basename}"`,
            loc: { line: 1 },
          });
        }
      },
    };
  },
};
