import { h as __exportAll } from "./pi-embedded-utils-7slQ9m7S.js";
import { r as defaultRuntime, t as createSubsystemLogger } from "./subsystem-Ci61Iebe.js";
import { i as formatCliCommand } from "./env-3oW17BWM.js";
import { o as logInfo } from "./exec-B5OgjUV4.js";
import { a as logoutWeb, t as resolveWhatsAppAccount } from "./accounts-TaYXhwSR.js";
import { n as loadConfig } from "./config-i4b9k_EZ.js";
import { i as waitForWaConnection, n as formatError, t as createWaSocket } from "./session-CPWoZj8I.js";
import { DisconnectReason } from "@whiskeysockets/baileys";

//#region src/web/login.ts
var login_exports = /* @__PURE__ */ __exportAll({ loginWeb: () => loginWeb });
const log = createSubsystemLogger("web/login");
async function loginWeb(verbose, waitForConnection, runtime = defaultRuntime, accountId) {
	const wait = waitForConnection ?? waitForWaConnection;
	const account = resolveWhatsAppAccount({
		cfg: loadConfig(),
		accountId
	});
	const sock = await createWaSocket(true, verbose, { authDir: account.authDir });
	logInfo("Waiting for WhatsApp connection...", runtime);
	try {
		await wait(sock);
		log.info("Linked! Credentials saved for future sends.");
	} catch (err) {
		const code = err?.error?.output?.statusCode ?? err?.output?.statusCode;
		if (code === 515) {
			log.info("WhatsApp asked for a restart after pairing (code 515); creds are saved. Restarting connection once…");
			try {
				sock.ws?.close();
			} catch {}
			const retry = await createWaSocket(false, verbose, { authDir: account.authDir });
			try {
				await wait(retry);
				log.info("Linked after restart; web session ready.");
				return;
			} finally {
				setTimeout(() => retry.ws?.close(), 500);
			}
		}
		if (code === DisconnectReason.loggedOut) {
			await logoutWeb({
				authDir: account.authDir,
				isLegacyAuthDir: account.isLegacyAuthDir,
				runtime
			});
			log.error(`WhatsApp reported the session is logged out. Cleared cached web session; please rerun ${formatCliCommand("minion channels login")} and scan the QR again.`);
			throw new Error("Session logged out; cache cleared. Re-run login.", { cause: err });
		}
		const formatted = formatError(err);
		log.error(`WhatsApp Web connection ended before fully opening. ${formatted}`);
		throw new Error(formatted, { cause: err });
	} finally {
		setTimeout(() => {
			try {
				sock.ws?.close();
			} catch {}
		}, 500);
	}
}

//#endregion
export { login_exports as n, loginWeb as t };