// NOTICE: This file is generated by Rollup. To modify it,
// please instead edit the ESM counterpart and rebuild with Rollup (npm run build).
'use strict';

const typeGuards = require('../../utils/typeGuards.cjs');
const validateTypes = require('../../utils/validateTypes.cjs');
const findNodeUpToRoot = require('../../utils/findNodeUpToRoot.cjs');
const isInDocument = require('../../utils/isInDocument.cjs');
const isStandardSyntaxDeclaration = require('../../utils/isStandardSyntaxDeclaration.cjs');
const atKeywords = require('../../reference/atKeywords.cjs');
const optionsMatches = require('../../utils/optionsMatches.cjs');
const report = require('../../utils/report.cjs');
const ruleMessages = require('../../utils/ruleMessages.cjs');
const validateOptions = require('../../utils/validateOptions.cjs');

const ruleName = 'no-invalid-position-declaration';

const messages = ruleMessages(ruleName, {
	rejected: 'Unexpected invalid position declaration',
});

const meta = {
	url: 'https://stylelint.io/user-guide/rules/no-invalid-position-declaration',
};

/** @type {import('stylelint').CoreRules[ruleName]} */
const rule = (primary, secondaryOptions) => {
	return (root, result) => {
		const validOptions = validateOptions(
			result,
			ruleName,
			{ actual: primary, possible: [true] },
			{
				actual: secondaryOptions,
				possible: {
					ignoreAtRules: [validateTypes.isString, validateTypes.isRegExp],
				},
				optional: true,
			},
		);

		if (!validOptions) return;

		/** @type {(node: import('postcss').Node) => boolean} */
		const isIgnoredAtRule = (node) =>
			typeGuards.isAtRule(node) && optionsMatches(secondaryOptions, 'ignoreAtRules', node.name);

		root.walkDecls((decl) => {
			// Skip checking declarations in embedded styles
			if (isInDocument(decl)) return;

			if (!isStandardSyntaxDeclaration(decl)) return;

			const { parent } = decl;

			if (!parent) return;

			// Declarations are allowed in rules
			if (typeGuards.isRule(parent)) return;

			if (typeGuards.isAtRule(parent)) {
				const atRuleName = parent.name.toLowerCase();

				// Nesting-supported at-rules only allow declarations when nested inside a rule
				if (atKeywords.nestingSupportedAtKeywords.has(atRuleName)) {
					const parentRule = findNodeUpToRoot(
						decl,
						(node) => typeGuards.isRule(node) || isIgnoredAtRule(node),
					);

					if (parentRule) return;
				} else {
					return;
				}
			}

			report({
				message: messages.rejected,
				messageArgs: [],
				node: decl,
				result,
				ruleName,
			});
		});
	};
};

rule.ruleName = ruleName;
rule.messages = messages;
rule.meta = meta;

module.exports = rule;
