import { GlobalConfig } from "../../../../config/global.js";
import { coerceString } from "../../../../util/string.js";
import { logger } from "../../../../logger/index.js";
import { joinUrlParts } from "../../../../util/url.js";
import { compile } from "../../../../util/template/index.js";
import { emojify } from "../../../../util/emoji.js";
import { hashBody } from "../../../../modules/platform/pr-body.js";
import { scm } from "../../../../modules/platform/scm.js";
import { platform } from "../../../../modules/platform/index.js";
import { getMigrationBranchName } from "../common.js";
import { ConfigMigrationCommitMessageFactory } from "../branch/commit-message.js";
import { prepareLabels } from "../../update/pr/labels.js";
import { addParticipants } from "../../update/pr/participants.js";
import { getPlatformPrOptions } from "../../update/pr/index.js";
import { isString } from "@sindresorhus/is";

//#region lib/workers/repository/config-migration/pr/index.ts
async function ensureConfigMigrationPr(config, migratedConfigData) {
	logger.debug("ensureConfigMigrationPr()");
	const docsLink = joinUrlParts(coerceString(config.productLinks?.documentation), "configuration-options/#configmigration");
	const branchName = getMigrationBranchName(config);
	const prTitle = new ConfigMigrationCommitMessageFactory(config, migratedConfigData.filename).getPrTitle();
	const existingPr = await platform.getBranchPr(branchName, config.baseBranch);
	const filename = migratedConfigData.filename;
	logger.debug("Filling in config migration PR template");
	let prBody = `The Renovate config in this repository needs migrating. Typically this is because one or more configuration options you are using have been renamed.

  You don't need to merge this PR right away, because Renovate will continue to migrate these fields internally each time it runs. But later some of these fields may be fully deprecated and the migrations removed. So it's a good idea to merge this migration PR soon. \n\n`;
	prBody += emojify(`

${filename.endsWith(".json5") ? `#### [PLEASE NOTE](${docsLink}): JSON5 config file migrated! All comments & trailing commas were removed.` : ""}

:no_bell: **Ignore**: Close this PR and you won't be reminded about config migration again, but one day your current config may no longer be valid.

:question: Got questions? Does something look wrong to you? Please don't hesitate to [request help here](${config.productLinks?.help}).\n\n`);
	if (isString(config.prHeader)) prBody = `${compile(config.prHeader, config)}\n\n${prBody}`;
	if (isString(config.prFooter)) prBody = `${prBody}\n---\n\n${compile(config.prFooter, config)}\n`;
	logger.trace({ prBody }, "prBody");
	prBody = platform.massageMarkdown(prBody, config.rebaseLabel);
	if (existingPr) {
		logger.debug("Found open migration PR");
		const prBodyHash = hashBody(prBody);
		if (existingPr.bodyStruct?.hash === prBodyHash && existingPr.title === prTitle) {
			logger.debug(`Pr does not need updating, PrNo: ${existingPr.number}`);
			return existingPr;
		}
		if (GlobalConfig.get("dryRun")) logger.info("DRY-RUN: Would update migration PR");
		else {
			await platform.updatePr({
				number: existingPr.number,
				prTitle,
				prBody
			});
			logger.info({ pr: existingPr.number }, "Migration PR updated");
		}
		return existingPr;
	}
	logger.debug("Creating migration PR");
	const labels = prepareLabels(config);
	try {
		if (GlobalConfig.get("dryRun")) logger.info("DRY-RUN: Would create migration PR");
		else {
			const pr = await platform.createPr({
				sourceBranch: branchName,
				targetBranch: config.defaultBranch,
				prTitle,
				prBody,
				labels,
				platformPrOptions: getPlatformPrOptions({
					...config,
					automerge: false
				})
			});
			logger.info({ pr: pr?.number }, "Migration PR created");
			if (pr) await addParticipants(config, pr);
			return pr;
		}
	} catch (err) {
		if (err.response?.statusCode === 422 && err.response?.body?.errors?.[0]?.message?.startsWith("A pull request already exists")) {
			logger.warn({ err }, "Migration PR already exists but cannot find it. It was probably created by a different user.");
			await scm.deleteBranch(branchName);
			return null;
		}
		throw err;
	}
	return null;
}

//#endregion
export { ensureConfigMigrationPr };
//# sourceMappingURL=index.js.map