import path from 'path';
/**
 * Rule: dependency/ignore-import-path
 * Ignore import path
 */
export default {
  meta: {
    type: 'problem',
    docs: {
      description: 'Ignore import path',
    },
    messages: {
      ignoreImportPath: 'Ignore import path: {{ path }}',
    },
    schema: [
      {
        type: 'object',
        properties: {
          ignoreImportPath: {
            type: 'array',
            items: {
              type: 'string',
            },
          },
        },
        additionalProperties: false,
      },
    ],
  },
  create(context) {
    const filePath = context.getFilename();

    // Get options - defaulting to include specific allowed circular dependencies
    const options = context.options[0] || {};
    const ignoreImportPath = options.ignoreImportPath || [];

    // Dynamically detect src path based on the current file path
    const currentFilePath = filePath;
    const srcPathMatch = currentFilePath.match(/(.*\/src)\//);
    const srcPath = srcPathMatch ? srcPathMatch[1] : path.resolve(path.dirname(filePath), '../..');
    // Alias map based on vite.config.ts
    const aliases = {
      '@': srcPath, // Dynamically resolved src path
    };

    // Resolve module path considering aliases and extensions
    function resolveModulePath(modulePath, baseDir) {
      // Handle aliases
      let resolvedPath = modulePath;
      for (const [alias, target] of Object.entries(aliases)) {
        if (modulePath.startsWith(alias)) {
          resolvedPath = path.join(target, modulePath.slice(alias.length));

          break;
        }
      }

      return path.resolve(baseDir, resolvedPath);
    }

    function checkImports(node) {
      if (node.type === 'ImportDeclaration') {
        const importPath = node.source.value;
        const dirName = path.dirname(filePath);
        let absoluteImportPath = resolveModulePath(importPath, dirName);

        const isIgnoreImportPath = ignoreImportPath.some(ignorePath => absoluteImportPath.endsWith(ignorePath));

        if (isIgnoreImportPath) {
          context.report({
            node,
            messageId: 'ignoreImportPath',
            data: {
              path: importPath,
            },
          });
        }
      }
    }

    return {
      ImportDeclaration: checkImports,
    };
  },
};
