import { fromBase64 } from "../../../../../../util/string.js";
import { logger } from "../../../../../../logger/index.js";
import { ForgejoHttp } from "../../../../../../util/http/forgejo.js";
import { Releases } from "../../../../../../modules/datasource/forgejo-releases/schema.js";
import { ContentsListResponse, RepoContents } from "../../../../../../modules/platform/forgejo/schema.js";
import { compareChangelogFilePath } from "../common.js";
import changelogFilenameRegex from "changelog-filename-regex";
//#region lib/workers/repository/update/pr/changelog/forgejo/index.ts
const id = "forgejo-changelog";
const http = new ForgejoHttp(id);
async function getReleaseNotesMd(repository, apiBaseUrl, sourceDirectory) {
	logger.trace("forgejo.getReleaseNotesMd()");
	const apiPrefix = `${apiBaseUrl}repos/${repository}/contents`;
	const sourceDir = sourceDirectory ? `/${sourceDirectory}` : "";
	const allFiles = (await http.getJson(`${apiPrefix}${sourceDir}`, { paginate: false }, ContentsListResponse)).body.filter((f) => f.type === "file");
	let files = [];
	if (!files.length) files = allFiles.filter((f) => changelogFilenameRegex.test(f.name));
	if (!files.length) {
		logger.trace("no changelog file found");
		return null;
	}
	const { path: changelogFile } = files.sort((a, b) => compareChangelogFilePath(a.path, b.path)).shift();
	/* istanbul ignore if */
	if (files.length !== 0) logger.debug(`Multiple candidates for changelog file, using ${changelogFile}`);
	const fileRes = await http.getJson(`${apiPrefix}/${changelogFile}`, RepoContents);
	// istanbul ignore if: should never happen
	if (fileRes.body.type !== "file" || !fileRes.body.content) {
		logger.debug(`Missing content for changelog file, using ${changelogFile}`);
		return null;
	}
	return {
		changelogFile,
		changelogMd: `${fromBase64(fileRes.body.content)}\n#\n##`
	};
}
async function getReleaseList(project, _release) {
	logger.trace("forgejo.getReleaseNotesMd()");
	const apiUrl = `${project.apiBaseUrl}repos/${project.repository}/releases`;
	return (await http.getJson(`${apiUrl}?draft=false`, { paginate: true }, Releases)).body.map((release) => ({
		url: `${project.baseUrl}${project.repository}/releases/tag/${release.tag_name}`,
		notesSourceUrl: apiUrl,
		name: release.name,
		body: release.body,
		tag: release.tag_name
	}));
}
//#endregion
export { getReleaseList, getReleaseNotesMd, id };

//# sourceMappingURL=index.js.map