/**
 * @license Copyright (c) 2017-2025, CKSource Holding sp. z o.o. All rights reserved.
 * For licensing, see LICENSE.md.
 */

'use strict';

const { linkToApi, linkToSdk, linkToGuide } = require( './parselinks' );

/**
 * Parses an href link from a string and returns the appropriate URL.
 *
 * @param {String} str The string containing the href link to parse
 * @param {Object} data The page data object
 * @param {Object} hexo The Hexo instance
 * @param {Object} options Options object
 * @param {Function} options.relativeUrlHelper Helper function to generate relative URLs
 * @param {Boolean} options.isSilentError Whether to silence error messages
 * @returns {String} The parsed URL
 */
module.exports = function parseHref( str, data, hexo, options ) {
	const { relativeUrlHelper, isSilentError } = options;
	const rgxp = /\\?{(?:@linkapi|@link|@linksdk|@linkexample)\s+[^{]+?({[^}]+})?[^{}]*\\?}/g;
	const match = rgxp.exec( str )?.[ 0 ];

	if ( !match ) {
		return str;
	}

	if ( match.includes( 'module:' ) || match.includes( '@linkapi' ) ) {
		return linkToApi( match, data, hexo, { relativeUrlHelper, isSilentError }, true );
	} else if ( match.includes( '@linksdk' ) || match.includes( '@linkexample' ) ) {
		return linkToSdk( match, data, hexo, { relativeUrlHelper, isSilentError }, true );
	} else {
		return linkToGuide( match, data, hexo, { relativeUrlHelper, isSilentError }, true );
	}
};
