import { FORGEJO_API_USING_HOST_TYPES, GITEA_API_USING_HOST_TYPES, GITHUB_API_USING_HOST_TYPES, GITLAB_API_USING_HOST_TYPES } from "../../constants/platforms.js";
import { isNonEmptyString, isString } from "@sindresorhus/is";

//#region lib/util/http/auth.ts
function applyAuthorization(inOptions) {
	const options = { ...inOptions };
	if (isNonEmptyString(options.headers?.authorization) || options.noAuth) return options;
	options.headers ??= {};
	if (options.token) {
		const authType = options.context?.authType;
		if (authType) if (authType === "Token-Only") options.headers.authorization = options.token;
		else options.headers.authorization = `${authType} ${options.token}`;
		else if (options.hostType && FORGEJO_API_USING_HOST_TYPES.includes(options.hostType)) options.headers.authorization = `Bearer ${options.token}`;
		else if (options.hostType && GITEA_API_USING_HOST_TYPES.includes(options.hostType)) options.headers.authorization = `Bearer ${options.token}`;
		else if (options.hostType && GITHUB_API_USING_HOST_TYPES.includes(options.hostType)) {
			options.headers.authorization = `token ${options.token}`;
			if (options.token.startsWith("x-access-token:")) {
				const appToken = options.token.replace("x-access-token:", "");
				options.headers.authorization = `token ${appToken}`;
				// v8 ignore else -- TODO: add test #40625
				if (isString(options.headers.accept)) options.headers.accept = options.headers.accept.replace("application/vnd.github.v3+json", "application/vnd.github.machine-man-preview+json");
			}
		} else if (options.hostType && GITLAB_API_USING_HOST_TYPES.includes(options.hostType)) if (options.token.length === 20) options.headers["Private-token"] = options.token;
		else options.headers.authorization = `Bearer ${options.token}`;
		else options.headers.authorization = `Bearer ${options.token}`;
		delete options.token;
	} else if (options.password !== void 0) {
		const auth = Buffer.from(`${options.username ?? ""}:${options.password}`).toString("base64");
		options.headers.authorization = `Basic ${auth}`;
		delete options.username;
		delete options.password;
	}
	return options;
}
function isAmazon(options) {
	return !!options.search?.includes("X-Amz-Algorithm");
}
function isAzureBlob(options) {
	return !!(options.hostname?.endsWith(".blob.core.windows.net") && options.href?.includes("/docker/registry"));
}
function removeAuthorization(options) {
	if (!options.password && !options.headers?.authorization) return;
	if (isAmazon(options) || isAzureBlob(options)) {
		// v8 ignore else -- TODO: add test #40625
		if (!options.href?.split?.("/")?.[2]?.split(":")?.[1]) delete options.port;
		// v8 ignore else -- TODO: add test #40625
		if (options?.headers?.authorization) delete options.headers.authorization;
		delete options.username;
		delete options.password;
	}
}

//#endregion
export { applyAuthorization, removeAuthorization };
//# sourceMappingURL=auth.js.map