import { existsSync, readFileSync } from 'fs';
import { checkExportInIndexFile } from '../utils/index.js';

/**
 * Rule: module-structure/require-index-export
 * Ensures that components, hooks, utils, interfaces, enums and types defined in a directory are exported from an index.ts file
 */
export default {
  meta: {
    type: 'suggestion',
    docs: {
      description: 'Ensures that components defined in a directory are exported from an index.ts file',
    },
  },
  create(context) {
    const filePath = context.getFilename();
    const pathParts = filePath.split(/[\\/]/);
    const folderPath = pathParts.slice(0, -1).join('/');
    const fileName = pathParts.pop();
    const isIndexFile = fileName === 'index.ts';

    // Skip if this is the index.ts file itself
    if (isIndexFile) {
      return {};
    }

    return {
      // Check for proper exports at the end of processing
      Program(node) {
        // Check if an index.ts file exists in the same directory
        const indexFilePath = `${folderPath}/index.ts`;
        if (!existsSync(indexFilePath)) {
          context.report({
            node: node,
            message: `No index.ts file found in the directory (${folderPath}). Create one to export the ${fileName}.`,
          });
          return;
        }

        // Check if the interface is exported in the index.ts file
        try {
          const indexFileContent = readFileSync(indexFilePath, 'utf8');
          const isExported = checkExportInIndexFile(indexFileContent, fileName);

          if (!isExported) {
            context.report({
              node: node,
              message: `The ${fileName} is not exported from the index.ts file. Add an export statement in the index.ts file.`,
            });
          }
        } catch (error) {
          // when reading the index file fails, skip the check
          console.warn(error);
        }
      },
    };
  },
};
