import { NextRequest, NextResponse } from 'next/server';
import { getSession } from '@/lib/session';
import { upsertPushSubscriptionD1 } from '@/lib/d1';

export async function POST(request: NextRequest) {
    try {
        const session = await getSession();
        if (!session?.user) {
            return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
        }

        const body = await request.json() as { subscription?: { endpoint: string; keys: { p256dh: string; auth: string } } };
        const { subscription } = body;
        if (!subscription) {
            return NextResponse.json({ error: 'Invalid subscription' }, { status: 400 });
        }

        const { endpoint, keys } = subscription;
        if (!endpoint || !keys || !keys.p256dh || !keys.auth) {
            return NextResponse.json({ error: 'Invalid subscription data' }, { status: 400 });
        }

        await upsertPushSubscriptionD1(
            session.user.id,
            endpoint,
            keys.p256dh,
            keys.auth
        );

        return NextResponse.json({ success: true });
    } catch (error) {
        console.error('Error saving subscription:', error);
        return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
    }
}
