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

'use strict';

const cheerio = require( 'cheerio' );
const upath = require( 'upath' );

/**
 * Support @errors tag.
 * Imports API errors HTML into a guide.
 */
hexo.extend.filter.register( 'after_post_render', page => {
	const errorsTagMatch = /{@errors}/.exec( page.content );
	// jscs:disable
	const relativeUrlHelper = hexo.extend.helper.store.relative_url;
	// jscs:enable

	if ( !errorsTagMatch || !hexo.projectGlobals[ page.projectName ] || !hexo.projectGlobals[ page.projectName ].errorsHtml ) {
		return;
	}

	const errorsHtml = hexo.projectGlobals[ page.projectName ].errorsHtml;
	const $ = cheerio.load( errorsHtml, null, false );

	// Errors are used in guides so links must be converted to have proper paths. Converting links to API here.
	$( 'a[href]' ).each( function() {
		const href = $( this ).attr( 'href' );

		// Ignore external links, error anchors and links with / which means they're not links to api.
		if ( /[a-z:]*\/\//.exec( href ) || /^#.*/.exec( href ) || href.split( '/' ).length > 1 ) {
			return;
		}

		const groups = hexo.projectGlobals[ page.projectName ].groups;
		const apiSlug = groups.find( g => g.id === 'api-reference' ).slug;
		const hrefPath = upath.join( page.BASE_PATH, apiSlug, href );

		$( this ).attr( 'href', relativeUrlHelper( page.path, hrefPath ) );
	} );

	// Converting links to guides created from {@glink}s.
	$( 'a[data-glink]' ).each( function() {
		const href = $( this ).attr( 'href' ).replace( '../', '' );
		const hrefPath = upath.join( page.BASE_PATH, href );

		$( this ).attr( 'href', relativeUrlHelper( page.path, hrefPath ) );
	} );

	page.content = page.content.replace( /<p[^>]*>{@errors}<\/p>/g, () => {
		return $.html();
	} );
}, 39 );
