import { arrayJoin, isDefined, isEmpty } from "ts-extras";
import { ruleCreator } from "../_internal/rule-creator.js";
const buildFixedTypeText = (sourceCode, unionType) => {
    let nonUndefinedTypeTexts = [];
    for (const typeNode of unionType.types) {
        if (typeNode.type === "TSUndefinedKeyword") {
            continue;
        }
        nonUndefinedTypeTexts = [
            ...nonUndefinedTypeTexts,
            sourceCode.getText(typeNode),
        ];
    }
    if (isEmpty(nonUndefinedTypeTexts) ||
        nonUndefinedTypeTexts.length === unionType.types.length) {
        return undefined;
    }
    return arrayJoin(nonUndefinedTypeTexts, " | ");
};
const unwrapExpression = (expression) => {
    if (expression.type === "TSAsExpression" ||
        expression.type === "TSSatisfiesExpression" ||
        expression.type === "TSNonNullExpression" ||
        expression.type === "TSTypeAssertion") {
        return unwrapExpression(expression.expression);
    }
    return expression;
};
const isDefinitelyDefinedExpression = (expression) => {
    const unwrappedExpression = unwrapExpression(expression);
    if (unwrappedExpression.type === "ArrayExpression") {
        return true;
    }
    if (unwrappedExpression.type === "ArrowFunctionExpression") {
        return true;
    }
    if (unwrappedExpression.type === "ClassExpression") {
        return true;
    }
    if (unwrappedExpression.type === "FunctionExpression") {
        return true;
    }
    if (unwrappedExpression.type === "Literal") {
        return true;
    }
    if (unwrappedExpression.type === "NewExpression") {
        return true;
    }
    if (unwrappedExpression.type === "ObjectExpression") {
        return true;
    }
    if (unwrappedExpression.type === "TemplateLiteral") {
        return true;
    }
    return false;
};
const isNeverReassigned = (sourceCode, declarator) => {
    const [declaredVariable] = sourceCode.getDeclaredVariables(declarator);
    if (declaredVariable === undefined) {
        return false;
    }
    return !declaredVariable.references.some((reference) => reference.isWrite() && reference.init !== true);
};
/**
 * Disallow redundant `undefined` unions on `var` declarations that are never
 * reassigned and initialized with definitely-defined values.
 */
const rule = ruleCreator({
    create: (context) => {
        const sourceCode = context.sourceCode;
        return {
            "VariableDeclaration[kind='var'] > VariableDeclarator[id.type='Identifier']": (node) => {
                const initializer = node.init;
                if (initializer === null) {
                    return;
                }
                if (!isDefinitelyDefinedExpression(initializer)) {
                    return;
                }
                if (!isNeverReassigned(sourceCode, node)) {
                    return;
                }
                const id = node.id;
                if (id.type !== "Identifier") {
                    return;
                }
                const typeAnnotation = id.typeAnnotation;
                if (typeAnnotation === undefined) {
                    return;
                }
                if (typeAnnotation.typeAnnotation.type !== "TSUnionType") {
                    return;
                }
                const fixedTypeText = buildFixedTypeText(sourceCode, typeAnnotation.typeAnnotation);
                if (!isDefined(fixedTypeText)) {
                    return;
                }
                const fix = (fixer) => fixer.replaceText(typeAnnotation.typeAnnotation, fixedTypeText);
                context.report({
                    fix,
                    messageId: "forbidden",
                    node: typeAnnotation.typeAnnotation,
                    suggest: [
                        {
                            fix,
                            messageId: "suggestRemoveRedundantUndefined",
                        },
                    ],
                });
            },
        };
    },
    defaultOptions: [],
    meta: {
        deprecated: false,
        docs: {
            deprecated: false,
            description: "disallow redundant `undefined` in `var` type unions when declarations are never reassigned and initialized with definitely-defined values.",
            frozen: false,
            recommended: false,
            url: "https://nick2bad4u.github.io/eslint-plugin-etc-misc/docs/rules/typescript-no-redundant-undefined-var",
        },
        fixable: "code",
        hasSuggestions: true,
        messages: {
            forbidden: "Never-reassigned `var` declarations with definitely-defined initializers should not redundantly include `undefined` in their type union.",
            suggestRemoveRedundantUndefined: "Remove redundant `undefined` from this `var` declaration type union.",
        },
        schema: [],
        type: "suggestion",
    },
    name: "typescript/no-redundant-undefined-var",
});
export default rule;
//# sourceMappingURL=typescript-no-redundant-undefined-var.js.map