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

export async function GET(request: NextRequest) {
  const rawToken = request.nextUrl.searchParams.get("token");

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

  const tokenHash = crypto
    .createHash("sha256")
    .update(rawToken)
    .digest("hex");

  const verificationToken = await prisma.emailVerificationToken.findUnique({
    where: { token: tokenHash },
    include: { user: true },
  });

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

  if (verificationToken.used) {
    return NextResponse.redirect(
      new URL("/login?verified=true", request.url)
    );
  }

  if (verificationToken.expiresAt < new Date()) {
    return NextResponse.redirect(
      new URL("/login?error=token-expired", request.url)
    );
  }

  await prisma.$transaction([
    prisma.user.update({
      where: { id: verificationToken.userId },
      data: { emailVerified: true },
    }),
    prisma.emailVerificationToken.update({
      where: { id: verificationToken.id },
      data: { used: true },
    }),
  ]);

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