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

/**
 * GET /auth/verify-email
 *
 * Verifies a user's email address using a token from the verification link.
 */
export async function GET(request: NextRequest) {
  const baseUrl = process.env.NEXTAUTH_URL || request.url;
  const searchParams = request.nextUrl.searchParams;
  const token = searchParams.get("token");
  const email = searchParams.get("email");

  if (!token || !email) {
    return NextResponse.redirect(
      new URL("/auth/error?error=InvalidToken", baseUrl)
    );
  }

  try {
    // Find verification token
    const verificationToken = await db.verificationToken.findUnique({
      where: {
        identifier_token: {
          identifier: email,
          token,
        },
      },
    });

    if (!verificationToken) {
      return NextResponse.redirect(
        new URL("/auth/error?error=InvalidToken", baseUrl)
      );
    }

    // Check if token is expired
    if (verificationToken.expires < new Date()) {
      // Clean up expired token
      await db.verificationToken.delete({
        where: {
          identifier_token: {
            identifier: email,
            token,
          },
        },
      });

      return NextResponse.redirect(
        new URL("/auth/error?error=TokenExpired", baseUrl)
      );
    }

    // Mark email as verified
    await db.user.update({
      where: { email },
      data: { emailVerified: new Date() },
    });

    // Delete used token
    await db.verificationToken.delete({
      where: {
        identifier_token: {
          identifier: email,
          token,
        },
      },
    });

    // Redirect to login with success message
    return NextResponse.redirect(
      new URL("/auth/login?verified=true", baseUrl)
    );
  } catch (error) {
    console.error("Email verification error:", error);
    return NextResponse.redirect(
      new URL("/auth/error?error=VerificationFailed", baseUrl)
    );
  }
}
