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

// 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 { generatePasswordResetToken, sendPasswordResetEmail } = await import('@/lib/email');
    
    const body = await request.json();
    const { email } = body;

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

    if (!isValidEmail(email)) {
      return NextResponse.json(
        { error: 'Please enter a valid email address' },
        { status: 400 }
      );
    }

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

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

    // Check if user is active
    if (user.isActive === false) {
      return NextResponse.json(
        { message: 'If an account with that email exists, a password reset email has been sent.' },
        { status: 200 }
      );
    }

    // Generate password reset token
    const resetToken = generatePasswordResetToken();
    const tokenExpiry = new Date();
    tokenExpiry.setHours(tokenExpiry.getHours() + 1); // Token expires in 1 hour

    // Update user with reset token
    await prismaAuth.user.update({
      where: { id: user.id },
      data: {
        passwordResetToken: resetToken,
        passwordResetTokenExpiry: tokenExpiry,
      },
    });

    // Send password reset email
    try {
      console.log('[FORGOT-PASSWORD] Attempting to send password reset email to:', user.email);
      await sendPasswordResetEmail(user.email, user.name, resetToken);
      console.log('[FORGOT-PASSWORD] Password reset email sent successfully to:', user.email);
    } catch (emailError: any) {
      console.error('[FORGOT-PASSWORD] Error sending password reset email:', emailError);
      console.error('[FORGOT-PASSWORD] Error details:', {
        message: emailError?.message,
        name: emailError?.name,
        response: emailError?.response,
        statusCode: emailError?.statusCode,
      });
      // Clear the token if email fails
      await prismaAuth.user.update({
        where: { id: user.id },
        data: {
          passwordResetToken: null,
          passwordResetTokenExpiry: null,
        },
      });
      return NextResponse.json(
        { 
          error: 'Failed to send password reset email',
          details: emailError?.message || 'Unknown error'
        },
        { status: 500 }
      );
    }

    return NextResponse.json(
      { message: 'If an account with that email exists, a password reset email has been sent.' },
      { status: 200 }
    );
  } catch (error: any) {
    console.error('Error processing password reset request:', error);
    return NextResponse.json(
      { error: 'Failed to process password reset request' },
      { status: 500 }
    );
  }
}

