import { loadAuthProfileStore, saveAuthProfileStore } from "./store.js";
//#region src/auth/profiles/oauth.ts
/** Resolve API key for a profile (handles OAuth refresh) */
async function resolveApiKeyForProfile(profileId, refreshFn) {
	const store = loadAuthProfileStore();
	const cred = store.profiles[profileId];
	if (!cred) return;
	if (cred.type === "api_key") return cred.key;
	if (cred.type === "token") {
		if (cred.expires && Date.now() >= cred.expires) return;
		return cred.token;
	}
	if (cred.type === "oauth") {
		const expires = cred.expires ?? 0;
		if (Date.now() >= expires) {
			if (cred.refresh && refreshFn) try {
				const refreshed = await refreshFn({
					refresh: cred.refresh,
					access: cred.access || "",
					expires: cred.expires || 0
				});
				store.profiles[profileId] = {
					...cred,
					access: refreshed.access,
					refresh: refreshed.refresh,
					expires: refreshed.expires
				};
				saveAuthProfileStore(store);
				return refreshed.access;
			} catch {
				return;
			}
			return;
		}
		return cred.access;
	}
}
/** Check if a profile has valid credentials */
function profileHasAuth(profileId) {
	const cred = loadAuthProfileStore().profiles[profileId];
	if (!cred) return false;
	if (cred.type === "api_key") return !!cred.key;
	if (cred.type === "token") {
		if (cred.expires && Date.now() >= cred.expires) return false;
		return !!cred.token;
	}
	if (cred.type === "oauth") {
		const expires = cred.expires ?? 0;
		return !!cred.access && Date.now() < expires;
	}
	return false;
}
/** Resolve profile for a provider (finds first available profile) */
function resolveProfileForProvider(provider, order) {
	const store = loadAuthProfileStore();
	const profileIds = order ?? store.order?.[provider];
	if (profileIds && profileIds.length > 0) {
		for (const profileId of profileIds) if (store.profiles[profileId]?.provider === provider && profileHasAuth(profileId)) return profileId;
	}
	for (const [profileId, cred] of Object.entries(store.profiles)) if (cred.provider === provider && profileHasAuth(profileId)) return profileId;
}
//#endregion
export { profileHasAuth, resolveApiKeyForProfile, resolveProfileForProvider };

//# sourceMappingURL=oauth.js.map