import { ruleCreator } from "../_internal/rule-creator.js";
const isRecordTypeReference = (typeNode) => typeNode.type === "TSTypeReference" &&
    typeNode.typeName.type === "Identifier" &&
    typeNode.typeName.name === "Record";
const isReadonlyWrappedRecord = (typeReference) => {
    const maybeTypeParameterInstantiation = typeReference.parent;
    if (maybeTypeParameterInstantiation?.type !== "TSTypeParameterInstantiation") {
        return false;
    }
    const maybeReadonlyTypeReference = maybeTypeParameterInstantiation.parent;
    return (maybeReadonlyTypeReference?.type === "TSTypeReference" &&
        maybeReadonlyTypeReference.typeName.type === "Identifier" &&
        maybeReadonlyTypeReference.typeName.name === "Readonly");
};
const collectMutableRecordTypeNodes = (typeNode) => {
    if (typeNode.type === "TSIntersectionType" ||
        typeNode.type === "TSUnionType") {
        return typeNode.types.flatMap((subTypeNode) => collectMutableRecordTypeNodes(subTypeNode));
    }
    if (!isRecordTypeReference(typeNode) || isReadonlyWrappedRecord(typeNode)) {
        return [];
    }
    return [typeNode];
};
const buildReadonlyRecordFix = (node) => (fixer) => [
    fixer.replaceText(node.typeName, "Readonly<Record"),
    fixer.insertTextAfter(node, ">"),
];
/**
 * Require readonly record type aliases.
 */
const rule = ruleCreator({
    create: (context) => ({
        TSTypeAliasDeclaration: (node) => {
            const mutableRecordTypeNodes = collectMutableRecordTypeNodes(node.typeAnnotation);
            for (const mutableRecordTypeNode of mutableRecordTypeNodes) {
                const fix = buildReadonlyRecordFix(mutableRecordTypeNode);
                context.report({
                    fix,
                    messageId: "forbidden",
                    node: mutableRecordTypeNode.typeName,
                    suggest: [
                        {
                            fix,
                            messageId: "suggestRequireReadonlyRecordTypeAlias",
                        },
                    ],
                });
            }
        },
    }),
    defaultOptions: [],
    meta: {
        deprecated: false,
        docs: {
            deprecated: false,
            description: "require Readonly<Record<...>> type alias annotations.",
            frozen: false,
            recommended: false,
            url: "https://nick2bad4u.github.io/eslint-plugin-etc-misc/docs/rules/typescript-require-readonly-record-type-alias",
        },
        fixable: "code",
        hasSuggestions: true,
        messages: {
            forbidden: "Prefer readonly record type aliases.",
            suggestRequireReadonlyRecordTypeAlias: "Convert this type alias annotation to Readonly<Record<...>>.",
        },
        schema: [],
        type: "suggestion",
    },
    name: "typescript/require-readonly-record-type-alias",
});
export default rule;
//# sourceMappingURL=typescript-require-readonly-record-type-alias.js.map