import { verifySolution } from "altcha-lib";

//#region src/utils/pow.ts
function isSentinelUpstreamUnavailable(error) {
	return error === "sentinel_network_error" || error === "sentinel_invalid_response";
}
const POW_ERROR_MESSAGES = {
	pow_expired: "Proof-of-work challenge has expired. Please request a new challenge.",
	pow_required: "Proof-of-work challenge solution is required.",
	pow_invalid: "Proof-of-work challenge solution is invalid."
};
function getPoWErrorMessage(error) {
	return POW_ERROR_MESSAGES[error];
}
function isPoWEnabled(hmacSecret) {
	return !!hmacSecret;
}
function isChallengeExpired(payload) {
	try {
		const salt = JSON.parse(atob(payload))?.salt;
		if (!salt) return false;
		const expires = new URLSearchParams(salt.split("?")[1] ?? "").get("expires");
		if (!expires) return false;
		return Date.now() / 1e3 > Number(expires);
	} catch {
		return false;
	}
}
async function verifyPoW(request, hmacSecret) {
	if (!hmacSecret) return { ok: true };
	const challengeHeader = request.headers.get("x-inkeep-challenge-solution");
	if (!challengeHeader) return {
		ok: false,
		error: "pow_required"
	};
	if (isChallengeExpired(challengeHeader)) return {
		ok: false,
		error: "pow_expired"
	};
	try {
		if (!await verifySolution(challengeHeader, hmacSecret, false)) return {
			ok: false,
			error: "pow_invalid"
		};
	} catch {
		return {
			ok: false,
			error: "pow_invalid"
		};
	}
	return { ok: true };
}
function isSentinelEnabled(apiKeyId) {
	return !!apiKeyId;
}
async function verifySentinelPayload(payload, sentinelBaseUrl, apiKeyId, apiKeySecret) {
	const url = `${sentinelBaseUrl}/v1/verify/signature?apiKey=${encodeURIComponent(apiKeyId)}&apiSecret=${encodeURIComponent(apiKeySecret)}`;
	let response;
	try {
		response = await fetch(url, {
			method: "POST",
			headers: { "Content-Type": "application/json" },
			body: JSON.stringify({ payload }),
			signal: AbortSignal.timeout(5e3)
		});
	} catch (err) {
		return {
			ok: false,
			error: "sentinel_network_error",
			reason: err instanceof Error ? err.message : "Network error"
		};
	}
	if (!response.ok) {
		let upstreamReason = `HTTP ${response.status}`;
		try {
			const errBody = await response.json();
			if (typeof errBody.error === "string") upstreamReason = errBody.error;
		} catch {}
		return {
			ok: false,
			error: "sentinel_verify_failed",
			reason: upstreamReason
		};
	}
	let body;
	try {
		body = await response.json();
	} catch (err) {
		const parseMessage = err instanceof Error ? err.message : String(err);
		return {
			ok: false,
			error: "sentinel_invalid_response",
			reason: `Non-JSON response (HTTP ${response.status}): ${parseMessage}`
		};
	}
	if (body.verified !== true) return {
		ok: false,
		error: "sentinel_rejected",
		reason: typeof body.reason === "string" ? body.reason : "Verification rejected"
	};
	return {
		ok: true,
		classification: typeof body.classification === "string" ? body.classification : "unknown",
		score: typeof body.score === "number" ? body.score : 0,
		verificationId: typeof body.verificationId === "string" ? body.verificationId : ""
	};
}

//#endregion
export { getPoWErrorMessage, isPoWEnabled, isSentinelEnabled, isSentinelUpstreamUnavailable, verifyPoW, verifySentinelPayload };