import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { logger } from '@/lib/logger';
import { checkRateLimit, getClientIp, AUTH_RATE_LIMITS } from '@/lib/rate-limit';

/**
 * GET /api/auth/verify-email
 *
 * Verifies a user's email address using a verification token
 * Token is provided via query params: ?token=xxx&email=xxx
 */
export async function GET(request: NextRequest) {
  const baseUrl = process.env.NEXTAUTH_URL || request.url;

  // Rate limit
  const ip = getClientIp(request.headers);
  const limit = checkRateLimit(`verify:${ip}`, AUTH_RATE_LIMITS.verifyEmail);
  if (!limit.allowed) {
    return NextResponse.redirect(
      new URL('/auth/error?error=TooManyRequests', baseUrl)
    );
  }

  const searchParams = request.nextUrl.searchParams;
  const token = searchParams.get('token');
  const email = searchParams.get('email');

  // Validate required parameters
  if (!token || !email) {
    logger.warn({ action: 'email_verification_failed', reason: 'missing_params' }, 'Email verification failed: missing token or email parameter');
    return NextResponse.redirect(
      new URL('/auth/error?error=InvalidToken', baseUrl)
    );
  }

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

    // Check token exists
    if (!verificationToken) {
      logger.warn({ action: 'email_verification_failed', reason: 'token_not_found' }, 'Email verification failed: token not found');
      return NextResponse.redirect(
        new URL('/auth/error?error=InvalidToken', baseUrl)
      );
    }

    // Check token hasn't expired
    if (verificationToken.expires < new Date()) {
      logger.warn({ action: 'email_verification_failed', reason: 'token_expired' }, 'Email verification failed: token expired');

      // 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() },
    });

    logger.info({ action: 'email_verified' }, 'Email verified successfully');

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

    // Redirect to dashboard with success message
    return NextResponse.redirect(
      new URL('/dashboard?verified=true', baseUrl)
    );
  } catch (error) {
    logger.error({ err: error, action: 'email_verification_error' }, 'Email verification error');
    return NextResponse.redirect(
      new URL('/auth/error?error=VerificationFailed', baseUrl)
    );
  }
}
