import { atRuleRegexes, mayIncludeRegexes } from '../../utils/regexes.mjs';
import { isRegExp, isString } from '../../utils/validateTypes.mjs';
import { atRuleParamIndex } from '../../utils/nodeFieldIndices.mjs';
import getAtRuleParams from '../../utils/getAtRuleParams.mjs';
import getRuleSelector from '../../utils/getRuleSelector.mjs';
import isStandardSyntaxAtRule from '../../utils/isStandardSyntaxAtRule.mjs';
import isStandardSyntaxRule from '../../utils/isStandardSyntaxRule.mjs';
import matchesStringOrRegExp from '../../utils/matchesStringOrRegExp.mjs';
import parseSelector from '../../utils/parseSelector.mjs';
import report from '../../utils/report.mjs';
import ruleMessages from '../../utils/ruleMessages.mjs';
import validateOptions from '../../utils/validateOptions.mjs';

const ruleName = 'selector-pseudo-class-disallowed-list';

const messages = ruleMessages(ruleName, {
	rejected: (selector) => `Disallowed pseudo-class "${selector}"`,
});

const meta = {
	url: 'https://stylelint.io/user-guide/rules/selector-pseudo-class-disallowed-list',
};

/** @import {AtRule, Rule} from 'postcss' */

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

		if (!validOptions) return;

		/**
		 * @param {string} selector
		 * @param {AtRule | Rule} node
		 * @param {number} offset
		 */
		function check(selector, node, offset = 0) {
			parseSelector(selector, result, node)?.walkPseudos(({ value, sourceIndex }) => {
				// Ignore pseudo-elements
				if (value.slice(0, 2) === '::') return;

				const name = value.slice(1);

				if (!matchesStringOrRegExp(name, primary)) return;

				const index = offset + sourceIndex;

				report({
					message: messages.rejected,
					messageArgs: [value],
					node,
					result,
					ruleName,
					index,
					endIndex: index + value.length,
				});
			});
		}

		root.walkRules(mayIncludeRegexes.pseudo, (ruleNode) => {
			if (!isStandardSyntaxRule(ruleNode)) return;

			check(getRuleSelector(ruleNode), ruleNode);
		});

		root.walkAtRules(atRuleRegexes.pageName, (atRuleNode) => {
			if (!mayIncludeRegexes.pseudo.test(atRuleNode.params)) return;

			if (!isStandardSyntaxAtRule(atRuleNode)) return;

			check(getAtRuleParams(atRuleNode), atRuleNode, atRuleParamIndex(atRuleNode));
		});
	};
};

rule.primaryOptionArray = true;
rule.ruleName = ruleName;
rule.messages = messages;
rule.meta = meta;
export default rule;
