// 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 validateTypes = require('../../utils/validateTypes.cjs');
const nodeFieldIndices = require('../../utils/nodeFieldIndices.cjs');
const regexes = require('../../utils/regexes.cjs');
const mediaTypes = require('../../reference/mediaTypes.cjs');
const mediaQueryListParser = require('@csstools/media-query-list-parser');
const isStandardSyntaxAtRule = require('../../utils/isStandardSyntaxAtRule.cjs');
const cssTokenizer = require('@csstools/css-tokenizer');
const optionsMatches = require('../../utils/optionsMatches.cjs');
const parseMediaQuery = require('../../utils/parseMediaQuery.cjs');
const report = require('../../utils/report.cjs');
const ruleMessages = require('../../utils/ruleMessages.cjs');
const cssParserAlgorithms = require('@csstools/css-parser-algorithms');
const validateOptions = require('../../utils/validateOptions.cjs');

const ruleName = 'media-type-no-deprecated';

const messages = ruleMessages(ruleName, {
	rejected: (mediaType) => `Unexpected deprecated media type "${mediaType}"`,
});

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

const DEPRECATED_MEDIA_TYPES_PATTERN = new RegExp(
	`\\b(${[...mediaTypes.deprecatedMediaTypesNames].join('|')})\\b`,
	'i',
);

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

		if (!validOptions) return;

		root.walkAtRules(regexes.atRuleRegexes.mediaName, (atRule) => {
			if (!isStandardSyntaxAtRule(atRule)) return;

			if (!DEPRECATED_MEDIA_TYPES_PATTERN.test(atRule.params)) return;

			const mediaQueryList = parseMediaQuery(atRule);

			mediaQueryList.forEach((mediaQuery) => {
				if (!mediaQueryListParser.isMediaQueryWithType(mediaQuery)) return;

				const mediaType = mediaQuery.getMediaType();

				if (!mediaTypes.deprecatedMediaTypesNames.has(mediaType.toLowerCase())) return;

				if (optionsMatches(secondaryOptions, 'ignoreMediaTypes', mediaType)) return;

				const atRuleIndex = nodeFieldIndices.atRuleParamIndex(atRule);
				const [index, endIndex] = cssParserAlgorithms.sourceIndices({
					tokens: () => mediaQuery.mediaType.filter(cssTokenizer.isTokenIdent),
				});

				report({
					message: messages.rejected,
					messageArgs: [mediaType],
					node: atRule,
					index: atRuleIndex + index,
					endIndex: atRuleIndex + endIndex + 1,
					ruleName,
					result,
				});
			});
		});
	};
};

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

module.exports = rule;
