import "../../../../../base64-CmWvODNW.mjs";
import "../../../../../types-CuW0zWDA.mjs";
import { t as apiError } from "../../../../../error-CkAseSqZ.mjs";
import { t as isSafeRedirect } from "../../../../../redirect-CoW3G-0U.mjs";
import { createKyselyAdapter } from "@emdash-cms/auth/adapters/kysely";
import { MagicLinkError, verifyMagicLink } from "@emdash-cms/auth";

//#region src/astro/routes/api/auth/magic-link/verify.ts
const prerender = false;
const GET = async ({ url, locals, session, redirect }) => {
	const { emdash } = locals;
	if (!emdash?.db) return apiError("NOT_CONFIGURED", "EmDash is not initialized", 500);
	const token = url.searchParams.get("token");
	if (!token) return redirect("/_emdash/admin/login?error=missing_token");
	try {
		const adapter = createKyselyAdapter(emdash.db);
		const user = await verifyMagicLink(adapter, token);
		adapter.deleteExpiredTokens().catch(() => {});
		if (session) session.set("user", { id: user.id });
		const rawRedirect = url.searchParams.get("redirect");
		return redirect(isSafeRedirect(rawRedirect) ? rawRedirect : "/_emdash/admin");
	} catch (error) {
		console.error("Magic link verify error:", error);
		if (error instanceof MagicLinkError) switch (error.code) {
			case "invalid_token": return redirect("/_emdash/admin/login?error=invalid_link");
			case "token_expired": return redirect("/_emdash/admin/login?error=link_expired");
			case "user_not_found": return redirect("/_emdash/admin/login?error=user_not_found");
		}
		return redirect("/_emdash/admin/login?error=verification_failed");
	}
};

//#endregion
export { GET, prerender };
//# sourceMappingURL=verify.mjs.map