import { NextResponse } from 'next/server';
import { authenticateToken, AuthenticatedRequest } from '@/lib/middleware';
import { verify as verifyTOTP } from 'otplib'; // Use functional verify
import pool from '@/lib/db';
import { RowDataPacket, ResultSetHeader } from 'mysql2';

async function handler(req: AuthenticatedRequest) {
    try {
        if (!req.user) {
            return NextResponse.json({ error: 'Obehörig' }, { status: 401 });
        }

        const { code } = await req.json();

        if (!code) {
            return NextResponse.json({ error: 'Verifieringskod krävs' }, { status: 400 });
        }

        // Get user's secret
        const [users] = await pool.query<RowDataPacket[]>(
            'SELECT two_factor_secret FROM users WHERE id = ?',
            [req.user.userId]
        );

        if (users.length === 0 || !users[0].two_factor_secret) {
            return NextResponse.json({ error: '2FA-konfiguration hittades inte' }, { status: 404 });
        }

        const secret = users[0].two_factor_secret;
        const cleanCode = code.replace(/\s/g, '');

        console.log(`[2FA Verify Debug] User: ${req.user.userId}, Code: ${cleanCode}`);

        // Functional verify(options) in v13
        const result = await verifyTOTP({
            token: cleanCode,
            secret: secret,
        });

        console.log(`[2FA Verify Debug] Result: ${result.valid}`);

        if (!result.valid) {
            return NextResponse.json({ error: 'Ogiltig verifieringskod' }, { status: 400 });
        }

        // Enable 2FA
        await pool.query<ResultSetHeader>(
            'UPDATE users SET two_factor_enabled = TRUE WHERE id = ?',
            [req.user.userId]
        );

        return NextResponse.json({
            success: true,
            message: '2FA har aktiverats framgångsrikt'
        });
    } catch (error) {
        console.error('2FA verification error:', error);
        return NextResponse.json({ error: 'Internt serverfel vid 2FA-verifiering' }, { status: 500 });
    }
}

export const POST = authenticateToken(handler);
