import { NextRequest, NextResponse } from 'next/server';
export const dynamic = 'force-dynamic';
import { prisma } from '@/lib/prisma';
import { sendVerificationEmail, generateVerificationCode, generateVerificationToken } from '@/lib/email';

export async function POST(request: NextRequest) {
    try {
        const { email } = await request.json();

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

        const user = await prisma.user.findUnique({
            where: { email },
            select: {
                id: true,
                emailVerified: true,
                emailVerificationExpires: true,
            },
        });

        if (!user) {
            // Don't reveal whether user exists
            return NextResponse.json({ message: 'If an account exists, a new code has been sent.' });
        }

        if (user.emailVerified) {
            return NextResponse.json({ message: 'Email is already verified.' });
        }

        // Rate limit: don't resend if last code was sent less than 60 seconds ago
        if (user.emailVerificationExpires) {
            const lastSent = new Date(user.emailVerificationExpires.getTime() - 15 * 60 * 1000);
            if (Date.now() - lastSent.getTime() < 60 * 1000) {
                return NextResponse.json(
                    { error: 'Please wait before requesting a new code.' },
                    { status: 429 }
                );
            }
        }

        const code = generateVerificationCode();
        const token = generateVerificationToken();
        const expires = new Date(Date.now() + 15 * 60 * 1000);

        await prisma.user.update({
            where: { id: user.id },
            data: {
                emailVerificationCode: code,
                emailVerificationToken: token,
                emailVerificationExpires: expires,
            },
        });

        try {
            await sendVerificationEmail(email, code, token);
        } catch (emailError) {
            console.error('Failed to resend verification email:', emailError);
            return NextResponse.json(
                { error: 'Failed to send email. Please try again later.' },
                { status: 500 }
            );
        }

        return NextResponse.json({ message: 'A new verification code has been sent.' });
    } catch (error) {
        console.error('Resend verification error:', error);
        return NextResponse.json(
            { error: 'Something went wrong' },
            { status: 500 }
        );
    }
}
