import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";

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

  if (!token) {
    return NextResponse.redirect(new URL("/auth/login?error=token_missing", request.url));
  }

  const record = await prisma.verifyToken.findUnique({ where: { token } });

  if (!record || record.expiresAt < new Date()) {
    await prisma.verifyToken.deleteMany({ where: { token } }).catch(() => {});
    return NextResponse.redirect(new URL("/auth/login?error=token_expired", request.url));
  }

  await prisma.user.update({
    where: { id: record.userId },
    data: { emailVerified: new Date() },
  });
  await prisma.verifyToken.delete({ where: { token } });

  return NextResponse.redirect(new URL("/auth/login?verified=1", request.url));
}
