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

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

        // Update newsletter status
        await pool.query<ResultSetHeader>(
            'UPDATE users SET newsletter_subscribed = ? WHERE id = ?',
            [subscribed, req.user.userId]
        );

        if (subscribed) {
            const [users] = await pool.query<import('mysql2').RowDataPacket[]>(
                'SELECT full_name, username FROM users WHERE id = ?',
                [req.user.userId]
            );
            if (users.length > 0) {
                const { sendWelcomeNewsletterEmail } = await import('@/lib/email');
                const name = users[0].full_name || users[0].username;
                sendWelcomeNewsletterEmail(req.user.email, name).catch(err => console.error('Failed to send newsletter welcome email:', err));
            }
        }

        return NextResponse.json({
            success: true,
            message: subscribed ? 'Du prenumererar nu på nyhetsbrevet.' : 'Du har avbrutit din prenumeration på nyhetsbrevet.'
        });
    } catch (error) {
        console.error('Newsletter toggle error:', error);
        return NextResponse.json({ error: 'Internt serverfel vid uppdatering av nyhetsbrev' }, { status: 500 });
    }
}

export const POST = authenticateToken(handler);
