// 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 valueParser = require('postcss-value-parser');
const validateTypes = require('../../utils/validateTypes.cjs');
const getDeclarationValue = require('../../utils/getDeclarationValue.cjs');
const isStandardSyntaxValue = require('../../utils/isStandardSyntaxValue.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 = 'annotation-no-unknown';

const messages = ruleMessages(ruleName, {
	rejected: (annotation) => `Unexpected unknown annotation "${annotation}"`,
});

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

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

		if (!validOptions) {
			return;
		}

		root.walkDecls(checkStatement);

		/**
		 * @param {import('postcss').Declaration} decl
		 */
		function checkStatement(decl) {
			if (!isStandardSyntaxValue(decl.value)) return;

			if (decl.important) return;

			if (!decl.value.includes('!')) return;

			const parsedValue = valueParser(getDeclarationValue(decl));

			parsedValue.walk((node) => {
				if (!isAnnotation(node)) return;

				const value = node.value;
				const tokenValue = value.slice(1);

				if (optionsMatches(secondaryOptions, 'ignoreAnnotations', tokenValue)) {
					return;
				}

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

		/**
		 * @param {valueParser.Node} node
		 */
		function isAnnotation(node) {
			return node.type === 'word' && node.value.startsWith('!');
		}
	};
};

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

module.exports = rule;
