import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { hashEmailVerificationToken } from "@/lib/email-verification";
import { getBaseAppUrl } from "@/lib/app-url";

export async function GET(request: Request) {
  const url = new URL(request.url);
  const appBaseUrl = getBaseAppUrl();
  const token = url.searchParams.get("token")?.trim() ?? "";
  const email = url.searchParams.get("email")?.toLowerCase().trim() ?? "";

  if (!token || !email) {
    return NextResponse.redirect(new URL("/login?verified=0", appBaseUrl));
  }

  const tokenHash = hashEmailVerificationToken(token);

  const record = await prisma.verificationToken.findFirst({
    where: {
      identifier: email,
      token: tokenHash,
      expires: { gt: new Date() },
    },
  });

  if (!record) {
    return NextResponse.redirect(new URL("/login?verified=0", appBaseUrl));
  }

  await prisma.$transaction(async (tx) => {
    await tx.user.update({
      where: { email },
      data: {
        emailVerified: new Date(),
        status: "active",
      },
    });

    await tx.verificationToken.delete({
      where: {
        identifier_token: {
          identifier: record.identifier,
          token: record.token,
        },
      },
    });
  });

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