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

// Force dynamic rendering to prevent Resend initialization during build
export const dynamic = 'force-dynamic';

export async function POST(request: NextRequest) {
  try {
    // Dynamically import email functions to avoid Resend initialization during build
    const { generateEmailConfirmationToken, sendEmailConfirmationResend } = await import('@/lib/email');
    
    const body = await request.json();
    const { email } = body;

    if (!email) {
      return NextResponse.json(
        { error: 'Email is required' },
        { status: 400 }
      );
    }

    // Find user
    const user = await prismaAuth.user.findUnique({
      where: { email },
    });

    if (!user) {
      // Don't reveal if user exists or not for security
      return NextResponse.json(
        { message: 'If an account with that email exists, a confirmation email has been sent.' },
        { status: 200 }
      );
    }

    // If already verified, don't send another email
    if (user.emailVerified) {
      return NextResponse.json(
        { message: 'Email is already verified.' },
        { status: 200 }
      );
    }

    // Generate new token
    const confirmationToken = generateEmailConfirmationToken();
    const tokenExpiry = new Date();
    tokenExpiry.setHours(tokenExpiry.getHours() + 24); // Token expires in 24 hours

    // Update user with new token
    await prismaAuth.user.update({
      where: { id: user.id },
      data: {
        emailConfirmationToken: confirmationToken,
        emailConfirmationTokenExpiry: tokenExpiry,
      },
    });

    // Send confirmation email
    try {
      await sendEmailConfirmationResend(user.email, user.name, confirmationToken);
    } catch (emailError) {
      console.error('Error sending confirmation email:', emailError);
      return NextResponse.json(
        { error: 'Failed to send confirmation email' },
        { status: 500 }
      );
    }

    return NextResponse.json(
      { message: 'Confirmation email has been sent. Please check your inbox.' },
      { status: 200 }
    );
  } catch (error: any) {
    console.error('Error resending confirmation email:', error);
    return NextResponse.json(
      { error: 'Failed to resend confirmation email', details: error.message },
      { status: 500 }
    );
  }
}







