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

'use strict';

const upath = require( 'upath' );

/**
 * This filter checks if every page contains necessary properties e.g. category.
 * These properties should be defined in guide's front matter.
 * This is the second filter run for each documentation page (except API docs).
 */
hexo.extend.filter.register( 'before_post_render', data => {
	if ( !hexo.projectGlobals || !hexo.projectGlobals[ data.projectName ] ) {
		return;
	}

	data.startPage = getStartPage();

	if ( !data.projectName || !data.BASE_PATH ) {
		throw new Error( `Internal: Missing properties in page data. File: ${ data.source }` );
	}

	const basePath = hexo.projectGlobals[ data.projectName ].BASE_PATH;
	// jscs:disable
	const fullSourcePath = data.full_source;
	// jscs:enable

	// no need to check project's index page
	if ( data.path === `${ basePath }/index.html` ) {
		return;
	}

	// check if category id is present
	if ( !data.category ) {
		throw new Error( `Document: ${ extractPath( fullSourcePath ) } has no category id.` );
	}

	// check if given category exists
	const categoryIds = hexo.projectGlobals[ data.projectName ].categoryIds;

	if ( !categoryIds || !categoryIds.has( data.category ) ) {
		throw new Error( `Document: ${ extractPath( fullSourcePath ) } is assigned to non-existent category.` );
	}

	if ( data.order === undefined ) {
		data.order = 0;
	}

	function extractPath( str ) {
		if ( typeof str !== 'string' ) {
			return;
		}

		// jscs:disable
		return str.replace( upath.join( hexo.source_dir, basePath ), '' );
		// jscs:enable
	}

	function getStartPage() {
		if ( hexo.projectGlobals[ data.projectName ].config.startPage ) {
			return '/' + hexo.projectGlobals[ data.projectName ].config.startPage;
		}

		return '/index.html';
	}
}, 5 );
