import { NextRequest, NextResponse } from 'next/server';
import pool from '@/lib/db';
import { RowDataPacket, ResultSetHeader } from 'mysql2';

export async function GET(req: NextRequest) {
    try {
        const { searchParams } = new URL(req.url);
        const token = searchParams.get('token');

        if (!token) {
            return NextResponse.redirect(new URL('/login?error=InvalidToken', req.url));
        }

        // Find user with this token
        const [users] = await pool.query<RowDataPacket[]>(
            'SELECT id FROM users WHERE verification_token = ?',
            [token]
        );

        if (users.length === 0) {
            return NextResponse.redirect(new URL('/login?error=InvalidToken', req.url));
        }

        const userId = users[0].id;

        // Update user as verified and clear token
        await pool.query<ResultSetHeader>(
            'UPDATE users SET email_verified = TRUE, verification_token = NULL WHERE id = ?',
            [userId]
        );

        return NextResponse.redirect(new URL('/login?verified=true', req.url));
    } catch (error) {
        console.error('Verification error:', error);
        return NextResponse.redirect(new URL('/login?error=ServerError', req.url));
    }
}
