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

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

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

    // Find user with this token
    const user = await prismaAuth.user.findUnique({
      where: { emailConfirmationToken: token },
    });

    if (!user) {
      return NextResponse.redirect(
        new URL('/login?error=invalid_token', request.url)
      );
    }

    // Check if token has expired
    if (user.emailConfirmationTokenExpiry && user.emailConfirmationTokenExpiry < new Date()) {
      return NextResponse.redirect(
        new URL('/login?error=token_expired', request.url)
      );
    }

    // Check if already verified
    if (user.emailVerified) {
      return NextResponse.redirect(
        new URL('/login?message=already_verified', request.url)
      );
    }

    // Verify the email
    await prismaAuth.user.update({
      where: { id: user.id },
      data: {
        emailVerified: true,
        emailConfirmationToken: null,
        emailConfirmationTokenExpiry: null,
      },
    });

    // Redirect to login with success message
    return NextResponse.redirect(
      new URL('/login?verified=true', request.url)
    );
  } catch (error: any) {
    console.error('Error verifying email:', error);
    return NextResponse.redirect(
      new URL('/login?error=verification_failed', request.url)
    );
  }
}







