/* eslint-disable @typescript-eslint/prefer-readonly-parameter-types -- ESLint fixer API callback signatures. */
import { arrayFirst, arrayJoin, arrayLast } from "ts-extras";
import { ruleCreator } from "../_internal/rule-creator.js";
const toName = (specifier) => specifier.exported.type === "Identifier"
    ? specifier.exported.name
    : specifier.exported.value;
const buildFix = (fixer, node, sourceCode, sorted) => {
    const startRange = arrayFirst(node.specifiers)?.range ?? node.range;
    const endRange = arrayLast(node.specifiers)?.range ?? node.range;
    return fixer.replaceTextRange([arrayFirst(startRange), arrayLast(endRange)], arrayJoin(sorted.map((specifier) => sourceCode.getText(specifier)), ", "));
};
/**
 * Enforce alphabetical sorting of named export specifiers.
 */
const rule = ruleCreator({
    create: (context) => ({
        ExportNamedDeclaration: (node) => {
            let exportSpecifiers = [];
            for (const specifier of node.specifiers) {
                if (specifier.type === "ExportSpecifier") {
                    exportSpecifiers = [...exportSpecifiers, specifier];
                }
            }
            if (exportSpecifiers.length < 2) {
                return;
            }
            // eslint-disable-next-line unicorn/no-array-sort -- Node >=16.0 support baseline
            const sorted = [...exportSpecifiers].sort((a, b) => toName(a).localeCompare(toName(b)));
            const unchanged = exportSpecifiers.every((specifier, index) => specifier === sorted[index]);
            if (unchanged) {
                return;
            }
            context.report({
                fix: (fixer) => buildFix(fixer, node, context.sourceCode, sorted),
                messageId: "incorrectSortingOrder",
                node,
            });
        },
    }),
    defaultOptions: [],
    meta: {
        deprecated: false,
        docs: {
            deprecated: false,
            description: "enforce alphabetical sorting of named export specifiers.",
            frozen: false,
            recommended: false,
            url: "https://nick2bad4u.github.io/eslint-plugin-etc-misc/docs/rules/sort-export-specifiers",
        },
        fixable: "code",
        hasSuggestions: false,
        messages: {
            incorrectSortingOrder: "Named export specifiers should be sorted alphabetically.",
        },
        schema: [],
        type: "suggestion",
    },
    name: "sort-export-specifiers",
});
export default rule;
/* eslint-enable @typescript-eslint/prefer-readonly-parameter-types -- Re-enable after file-scoped fixer callback implementations. */
//# sourceMappingURL=sort-export-specifiers.js.map