import { NextResponse } from "next/server";
import { db } from "@/app/db/db";
import { verificationTokens } from "@/app/db/schema/users";
import { eq } from "drizzle-orm";

export async function GET(request: Request) {
  const url = new URL(request.url);
  const error = url.searchParams.get("error");
  const token = url.searchParams.get("token");

  // Capture where the user came from
  const referer = request.headers.get("referer");
  const forwardedFor = request.headers.get("x-forwarded-for");
  const host = request.headers.get("host");

  let tokenRecord = null;

  if (token) {
    try {
      tokenRecord = await db
        .select()
        .from(verificationTokens)
        .where(eq(verificationTokens.token, token))
        .limit(1);
    } catch (err) {
      console.error("Error querying verificationTokens", err);
    }
  }

  console.error("Auth error callback triggered", {
    error,
    timestamp: new Date().toISOString(),
    path: url.pathname,
    query: Object.fromEntries(url.searchParams),

    userAgent: request.headers.get("user-agent"),
    referer,
    forwardedFor,
    host,

    tokenPresentInQuery: Boolean(token),
    tokenMatchedDB: Boolean(tokenRecord?.length),
    tokenDBRecord: tokenRecord?.[0] ?? null,
  });

  const redirectUrl = new URL("/auth/error", request.url);
  if (error) redirectUrl.searchParams.set("error", error);

  return NextResponse.redirect(redirectUrl);
}
