import { q as query } from '../../../chunks/db_Du3AmLCY.mjs';
import { s as signUserToken, b as setUserCookie } from '../../../chunks/user-auth_D4NBmYxs.mjs';
export { renderers } from '../../../renderers.mjs';

const GET = async ({ request, redirect }) => {
  try {
    const url = new URL(request.url);
    const token = url.searchParams.get("token");
    const isLogin = url.searchParams.get("login") === "1";
    if (!token) return redirect("/");
    let user;
    if (isLogin) {
      const result = await query(
        "SELECT id, email FROM users WHERE magic_link_token = $1 AND magic_link_expires_at > NOW()",
        [token]
      );
      if (!result.rows.length) {
        return redirect("/?error=expired");
      }
      user = result.rows[0];
      await query("UPDATE users SET magic_link_token = NULL, magic_link_expires_at = NULL, email_verified = true WHERE id = $1", [user.id]);
    } else {
      const result = await query(
        "SELECT id, email FROM users WHERE verification_token = $1",
        [token]
      );
      if (!result.rows.length) {
        return redirect("/?error=invalid");
      }
      user = result.rows[0];
      await query("UPDATE users SET email_verified = true, verification_token = NULL WHERE id = $1", [user.id]);
    }
    const jwt = signUserToken({ id: user.id, email: user.email });
    return new Response(null, {
      status: 302,
      headers: {
        "Location": "/watchlist",
        "Set-Cookie": setUserCookie(jwt)
      }
    });
  } catch (err) {
    console.error("Verify error:", err);
    return new Response("Er ging iets mis", { status: 500 });
  }
};

const _page = /*#__PURE__*/Object.freeze(/*#__PURE__*/Object.defineProperty({
  __proto__: null,
  GET
}, Symbol.toStringTag, { value: 'Module' }));

const page = () => _page;

export { page };
