import { NextResponse } from 'next/server';
import { authenticateToken, AuthenticatedRequest } from '@/lib/middleware';
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 });
        }

        // Disable 2FA by resetting enabled flag and secret
        await pool.query<ResultSetHeader>(
            'UPDATE users SET two_factor_enabled = FALSE, two_factor_secret = NULL WHERE id = ?',
            [req.user.userId]
        );

        return NextResponse.json({
            success: true,
            message: 'Tvåfaktorsautentisering har inaktiverats framgångsrikt.'
        });
    } catch (error) {
        console.error('Disable 2FA error:', error);
        return NextResponse.json({ error: 'Internt serverfel vid inaktivering av 2FA' }, { status: 500 });
    }
}

export const POST = authenticateToken(handler);
