import { passthrough } from 'p-transform';
import { isFileStateModified } from 'mem-fs-editor/state';
import ESLint from 'eslint';
import { Minimatch } from 'minimatch';
import { getPackageRoot } from '../../../lib/index.mjs';
export const createESLintTransform = function (transformOptions = {}) {
    const { extensions = 'js,ts', ignoreErrors } = transformOptions;
    const minimatch = new Minimatch(`**/*.{${extensions}}`, { dot: true });
    const eslint = new ESLint.ESLint({
        fix: true,
        useEslintrc: false,
        resolvePluginsRelativeTo: getPackageRoot(),
        overrideConfig: {
            plugins: ['unused-imports', 'import'],
            extends: ['plugin:@typescript-eslint/base'],
            parserOptions: {
                sourceType: 'module',
                ecmaVersion: 'latest',
            },
            rules: {
                'import/order': 'error',
                'import/no-duplicates': 'error',
                'unused-imports/no-unused-imports': 'error',
                'unused-imports/no-unused-vars': ['warn', { vars: 'all', varsIgnorePattern: '^_', args: 'after-used', argsIgnorePattern: '^_' }],
            },
        },
    });
    return passthrough(async (file) => {
        if (!minimatch.match(file.path) || !isFileStateModified(file)) {
            return;
        }
        try {
            if (await eslint.isPathIgnored(file.path)) {
                return;
            }
            const [result] = await eslint.lintText(file.contents.toString(), { filePath: file.path });
            if (result.output) {
                file.contents = Buffer.from(result.output);
            }
        }
        catch (error) {
            if (ignoreErrors) {
                this?.log?.warn?.(error);
                return;
            }
            throw error;
        }
    });
};
