import { NextResponse } from 'next/server';
import { authenticateToken, AuthenticatedRequest } from '@/lib/middleware';
import { generateSecret, generateURI } from 'otplib'; // Use functional exports
import QRCode from 'qrcode';
import pool from '@/lib/db';
import { ResultSetHeader } from 'mysql2';

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

        const userEmail = req.user.email;
        // functional generateSecret()
        const secret = generateSecret();

        // functional generateURI(options)
        const otpauth = generateURI({
            secret,
            label: userEmail,
            issuer: 'Nordic Storium',
        });

        const qrCodeDataUrl = await QRCode.toDataURL(otpauth);

        console.log(`[2FA Setup Debug] User: ${req.user.userId}, Secret Generated: ${secret}`);

        // Store the secret temporarily (unverified). 
        await pool.query<ResultSetHeader>(
            'UPDATE users SET two_factor_secret = ? WHERE id = ?',
            [secret, req.user.userId]
        );

        return NextResponse.json({
            qrCodeDataUrl,
            secret,
        });
    } catch (error) {
        console.error('2FA setup error:', error);
        return NextResponse.json({ error: 'Internt serverfel vid 2FA-konfiguration' }, { status: 500 });
    }
}

export const GET = authenticateToken(handler);
