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

/**
 * POST /api/auth/resend-verification
 *
 * Resends verification email to the currently logged-in user
 * Requires active session with unverified email
 */
export async function POST(request: NextRequest) {
  try {
    // Rate limit
    const ip = getClientIp(request.headers);
    const limit = checkRateLimit(`resend:${ip}`, AUTH_RATE_LIMITS.resendVerification);
    if (!limit.allowed) {
      return NextResponse.json(
        { error: 'Too many requests. Please try again later.' },
        { status: 429, headers: { 'Retry-After': String(Math.ceil((limit.resetAt - Date.now()) / 1000)) } }
      );
    }

    // Get current session
    const session = await auth();

    if (!session?.user?.email) {
      return NextResponse.json({ error: 'Not authenticated' }, { status: 401 });
    }

    // Check if user exists and is not verified
    const user = await db.user.findUnique({
      where: { email: session.user.email },
      select: { emailVerified: true },
    });

    if (!user) {
      return NextResponse.json({ error: 'User not found' }, { status: 404 });
    }

    if (user.emailVerified) {
      return NextResponse.json({ error: 'Email already verified' }, { status: 400 });
    }

    // Delete any existing verification tokens for this email
    await db.verificationToken.deleteMany({
      where: { identifier: session.user.email },
    });

    // Generate new token
    const token = crypto.randomBytes(32).toString('hex');
    const expires = new Date(Date.now() + 24 * 60 * 60 * 1000); // 24 hours

    await db.verificationToken.create({
      data: {
        identifier: session.user.email,
        token,
        expires,
      },
    });

    // Send verification email
    const verifyUrl = `${process.env.NEXTAUTH_URL}/auth/verify-email?token=${token}&email=${encodeURIComponent(session.user.email)}`;

    try {
      await sendVerificationEmail({
        email: session.user.email,
        url: verifyUrl,
        expires,
      });

      return NextResponse.json({
        message: 'Verification email sent successfully',
      });
    } catch (emailError) {
      logger.error({ err: emailError, action: 'resend_verification_email' }, 'Failed to send verification email');
      return NextResponse.json(
        { error: 'Failed to send email. Please try again later.' },
        { status: 500 }
      );
    }
  } catch (error) {
    logger.error({ err: error, action: 'resend_verification' }, 'Resend verification error');
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}
