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

'use strict';

const githubUrlUtils = require( '../../../src/helpers/github-url' );

/**
 * Gets url to project repository.
 * If a project consists of various packages/sub-repos, guides may be stored in these repos.
 * In order to create 'Report an issue' and 'Contribute to guide' links, each guide needs its repo url.
 */
hexo.extend.filter.register( 'before_post_render', data => {
	if ( !hexo.projectGlobals || !hexo.projectGlobals[ data.projectName ] ) {
		return;
	}

	const projectConfig = hexo.projectGlobals[ data.projectName ];
	const pagePaths = projectConfig.pagePaths || [];
	const pagePathData = pagePaths.find( p => p.newDataPath === data.path );
	const oldPath = pagePathData ? pagePathData.oldDataPath : '';

	if ( !oldPath ) {
		return;
	}

	const guidesToRepos = projectConfig.guidesToRepos;
	let pathKey = oldPath
		.replace( data.BASE_PATH, '' )
		.replace( '.html', '.md' );

	if ( data.issuesUrl === undefined || data.issuesUrl === true ) {
		data.issuesUrl = githubUrlUtils.getIssueUrl( projectConfig.config );
	}

	const repoUrlDocs = guidesToRepos.default;
	const contributeUrl = projectConfig.config.contributeUrl;

	// A flag that indicates whether the "docs/" part should be added during the link generation.
	// Why? Follow the thread below.
	let doNotAddDocsInPath = false;

	// If the guide has own repository, we need to a little adjust the value.
	if ( guidesToRepos[ pathKey ] ) {
		// First of all, do not add "docs/" into the generated URL.
		doNotAddDocsInPath = true;

		// The monorepo has the same `packageJson.repository` URL across all guides.
		// But for the guides we append `packageJson.repository.directory` if a package located in monorepo has it specified.
		// After removing the common values, we have a direct path to the guide (the directory)
		pathKey = guidesToRepos[ pathKey ].replace( repoUrlDocs, '' ) + pathKey;

		// Since each CKEditor 5's package has own `docs/` directory, we need to add the directory manually.
		// Before: `/package/ckeditor5-package/features/foo.md`
		// After: `/package/ckeditor5-package/docs/features/foo.md`
		// That's why we need to disable adding `docs/` part in the `githubUrlUtils.getContributeUrl()` util.
		pathKey = pathKey.split( '/' );
		pathKey.splice( 3, 0, 'docs' );
		pathKey = pathKey.join( '/' );
	}

	if ( data.contributeUrl === undefined || data.issuesUrl === true ) {
		data.contributeUrl = githubUrlUtils.getContributeUrl( { contributeUrl, repoUrlDocs, doNotAddDocsInPath }, pathKey );
	}
} );
