import { i as __exportAll } from "./tool-display-B7qTeoCS.js";
import { t as createSubsystemLogger } from "./subsystem-ocBR131w.js";
import { n as defaultRuntime } from "./runtime-CRvfzclG.js";
import { o as logInfo } from "./exec-CZr_EJHt.js";
import { t as formatCliCommand } from "./command-format-Dh6J8CvS.js";
import { o as loadConfig } from "./config-DJ3A5x_1.js";
import { n as resolveWhatsAppAccount, o as logoutWeb } from "./accounts-BZv5WxME.js";
import { i as waitForWaConnection, n as formatError, t as createWaSocket } from "./session-DJ0XyGh5.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 };