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 });
        }

        // Delete user account (CASCADE will handle user_sessions)
        await pool.query<ResultSetHeader>(
            'DELETE FROM users WHERE id = ?',
            [req.user.userId]
        );

        return NextResponse.json({
            success: true,
            message: 'Ditt konto har tagits bort framgångsrikt.'
        });
    } catch (error) {
        console.error('Delete account error:', error);
        return NextResponse.json({ error: 'Internt serverfel vid borttagning av konto' }, { status: 500 });
    }
}

export const DELETE = authenticateToken(handler);
