import { NextResponse } from 'next/server';
import pool from '@/lib/db';
import { verify as verifyTOTP } from 'otplib'; // Use functional verify from otplib
import { generateToken } from '@/lib/auth'; // Our own generateToken
import { RowDataPacket } from 'mysql2';

export async function POST(req: Request) {
    try {
        const { userId, code } = await req.json();

        if (!userId || !code) {
            return NextResponse.json(
                { error: 'Användar-ID och verifieringskod krävs' },
                { status: 400 }
            );
        }

        const [users] = await pool.query<RowDataPacket[]>(
            'SELECT * FROM users WHERE id = ?',
            [userId]
        );

        if (users.length === 0) {
            return NextResponse.json(
                { error: 'Användaren hittades inte' },
                { status: 404 }
            );
        }

        const user = users[0];

        if (!user.two_factor_enabled || !user.two_factor_secret) {
            return NextResponse.json(
                { error: '2FA är inte aktiverat för detta konto' },
                { status: 400 }
            );
        }

        const secret = user.two_factor_secret;
        const cleanCode = code.replace(/\s/g, '');

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

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

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

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

        // Generate final token
        const token = generateToken({
            userId: user.id,
            email: user.email,
            role: user.role,
        });

        return NextResponse.json({
            token,
            user: {
                id: user.id,
                email: user.email,
                name: user.full_name || user.username,
                role: user.role,
                created_at: user.created_at,
                email_verified: !!user.email_verified,
                two_factor_enabled: !!user.two_factor_enabled,
                newsletter_subscribed: !!user.newsletter_subscribed,
                personnummer: user.personnummer,
                mobile: user.mobile,
                address: user.address,
                zip_code: user.zip_code,
                city: user.city,
                country: user.country
            }
        });
    } catch (error) {
        console.error('2FA login error:', error);
        return NextResponse.json(
            { error: 'Internt serverfel' },
            { status: 500 }
        );
    }
}
