import { n as normalizeAccountId, t as DEFAULT_ACCOUNT_ID } from "./account-id-JwW97xNZ.js";
import { t as createAccountListHelpers } from "./account-helpers-BqSrsCej.js";
import { t as resolveAccountEntry } from "./account-lookup-Dr1S5Vra.js";
import { O as resolveOAuthDir, _ as info, b as success, h as defaultRuntime, i as jidToE164, o as resolveUserPath, x as getChildLogger } from "./utils-BtDYyj9L.js";
import fs from "node:fs/promises";
import path from "node:path";
import fs$1 from "node:fs";

//#region src/web/auth-store.ts
function resolveDefaultWebAuthDir() {
	return path.join(resolveOAuthDir(), "whatsapp", DEFAULT_ACCOUNT_ID);
}
const WA_WEB_AUTH_DIR = resolveDefaultWebAuthDir();
function resolveWebCredsPath(authDir) {
	return path.join(authDir, "creds.json");
}
function resolveWebCredsBackupPath(authDir) {
	return path.join(authDir, "creds.json.bak");
}
function readCredsJsonRaw(filePath) {
	try {
		if (!fs$1.existsSync(filePath)) return null;
		const stats = fs$1.statSync(filePath);
		if (!stats.isFile() || stats.size <= 1) return null;
		return fs$1.readFileSync(filePath, "utf-8");
	} catch {
		return null;
	}
}
function maybeRestoreCredsFromBackup(authDir) {
	const logger = getChildLogger({ module: "web-session" });
	try {
		const credsPath = resolveWebCredsPath(authDir);
		const backupPath = resolveWebCredsBackupPath(authDir);
		const raw = readCredsJsonRaw(credsPath);
		if (raw) {
			JSON.parse(raw);
			return;
		}
		const backupRaw = readCredsJsonRaw(backupPath);
		if (!backupRaw) return;
		JSON.parse(backupRaw);
		fs$1.copyFileSync(backupPath, credsPath);
		try {
			fs$1.chmodSync(credsPath, 384);
		} catch {}
		logger.warn({ credsPath }, "restored corrupted WhatsApp creds.json from backup");
	} catch {}
}
async function webAuthExists(authDir = resolveDefaultWebAuthDir()) {
	const resolvedAuthDir = resolveUserPath(authDir);
	maybeRestoreCredsFromBackup(resolvedAuthDir);
	const credsPath = resolveWebCredsPath(resolvedAuthDir);
	try {
		await fs.access(resolvedAuthDir);
	} catch {
		return false;
	}
	try {
		const stats = await fs.stat(credsPath);
		if (!stats.isFile() || stats.size <= 1) return false;
		const raw = await fs.readFile(credsPath, "utf-8");
		JSON.parse(raw);
		return true;
	} catch {
		return false;
	}
}
async function clearLegacyBaileysAuthState(authDir) {
	const entries = await fs.readdir(authDir, { withFileTypes: true });
	const shouldDelete = (name) => {
		if (name === "oauth.json") return false;
		if (name === "creds.json" || name === "creds.json.bak") return true;
		if (!name.endsWith(".json")) return false;
		return /^(app-state-sync|session|sender-key|pre-key)-/.test(name);
	};
	await Promise.all(entries.map(async (entry) => {
		if (!entry.isFile()) return;
		if (!shouldDelete(entry.name)) return;
		await fs.rm(path.join(authDir, entry.name), { force: true });
	}));
}
async function logoutWeb(params) {
	const runtime = params.runtime ?? defaultRuntime;
	const resolvedAuthDir = resolveUserPath(params.authDir ?? resolveDefaultWebAuthDir());
	if (!await webAuthExists(resolvedAuthDir)) {
		runtime.log(info("No WhatsApp Web session found; nothing to delete."));
		return false;
	}
	if (params.isLegacyAuthDir) await clearLegacyBaileysAuthState(resolvedAuthDir);
	else await fs.rm(resolvedAuthDir, {
		recursive: true,
		force: true
	});
	runtime.log(success("Cleared WhatsApp Web credentials."));
	return true;
}
function readWebSelfId(authDir = resolveDefaultWebAuthDir()) {
	try {
		const credsPath = resolveWebCredsPath(resolveUserPath(authDir));
		if (!fs$1.existsSync(credsPath)) return {
			e164: null,
			jid: null
		};
		const raw = fs$1.readFileSync(credsPath, "utf-8");
		const jid = JSON.parse(raw)?.me?.id ?? null;
		return {
			e164: jid ? jidToE164(jid, { authDir }) : null,
			jid
		};
	} catch {
		return {
			e164: null,
			jid: null
		};
	}
}

//#endregion
//#region src/web/accounts.ts
const { listConfiguredAccountIds, listAccountIds, resolveDefaultAccountId } = createAccountListHelpers("whatsapp");
const resolveDefaultWhatsAppAccountId = resolveDefaultAccountId;
function resolveAccountConfig(cfg, accountId) {
	return resolveAccountEntry(cfg.channels?.whatsapp?.accounts, accountId);
}
function resolveDefaultAuthDir(accountId) {
	return path.join(resolveOAuthDir(), "whatsapp", normalizeAccountId(accountId));
}
function resolveLegacyAuthDir() {
	return resolveOAuthDir();
}
function legacyAuthExists(authDir) {
	try {
		return fs$1.existsSync(path.join(authDir, "creds.json"));
	} catch {
		return false;
	}
}
function resolveWhatsAppAuthDir(params) {
	const accountId = params.accountId.trim() || DEFAULT_ACCOUNT_ID;
	const configured = resolveAccountConfig(params.cfg, accountId)?.authDir?.trim();
	if (configured) return {
		authDir: resolveUserPath(configured),
		isLegacy: false
	};
	const defaultDir = resolveDefaultAuthDir(accountId);
	if (accountId === DEFAULT_ACCOUNT_ID) {
		const legacyDir = resolveLegacyAuthDir();
		if (legacyAuthExists(legacyDir) && !legacyAuthExists(defaultDir)) return {
			authDir: legacyDir,
			isLegacy: true
		};
	}
	return {
		authDir: defaultDir,
		isLegacy: false
	};
}
function resolveWhatsAppAccount(params) {
	const rootCfg = params.cfg.channels?.whatsapp;
	const accountId = params.accountId?.trim() || resolveDefaultWhatsAppAccountId(params.cfg);
	const accountCfg = resolveAccountConfig(params.cfg, accountId);
	const enabled = accountCfg?.enabled !== false;
	const { authDir, isLegacy } = resolveWhatsAppAuthDir({
		cfg: params.cfg,
		accountId
	});
	return {
		accountId,
		name: accountCfg?.name?.trim() || void 0,
		enabled,
		sendReadReceipts: accountCfg?.sendReadReceipts ?? rootCfg?.sendReadReceipts ?? true,
		messagePrefix: accountCfg?.messagePrefix ?? rootCfg?.messagePrefix ?? params.cfg.messages?.messagePrefix,
		authDir,
		isLegacyAuthDir: isLegacy,
		selfChatMode: accountCfg?.selfChatMode ?? rootCfg?.selfChatMode,
		dmPolicy: accountCfg?.dmPolicy ?? rootCfg?.dmPolicy,
		allowFrom: accountCfg?.allowFrom ?? rootCfg?.allowFrom,
		groupAllowFrom: accountCfg?.groupAllowFrom ?? rootCfg?.groupAllowFrom,
		groupPolicy: accountCfg?.groupPolicy ?? rootCfg?.groupPolicy,
		textChunkLimit: accountCfg?.textChunkLimit ?? rootCfg?.textChunkLimit,
		chunkMode: accountCfg?.chunkMode ?? rootCfg?.chunkMode,
		mediaMaxMb: accountCfg?.mediaMaxMb ?? rootCfg?.mediaMaxMb,
		blockStreaming: accountCfg?.blockStreaming ?? rootCfg?.blockStreaming,
		ackReaction: accountCfg?.ackReaction ?? rootCfg?.ackReaction,
		groups: accountCfg?.groups ?? rootCfg?.groups,
		debounceMs: accountCfg?.debounceMs ?? rootCfg?.debounceMs
	};
}

//#endregion
export { readWebSelfId as a, resolveWebCredsPath as c, readCredsJsonRaw as i, webAuthExists as l, logoutWeb as n, resolveDefaultWebAuthDir as o, maybeRestoreCredsFromBackup as r, resolveWebCredsBackupPath as s, resolveWhatsAppAccount as t };