import { NextRequest, NextResponse } from 'next/server';
import { supabase } from '@/lib/supabase';
import { sendPushNotification } from '@/lib/webPush';
import type { SystemNotificationPayload } from '@/app/types/notifications';

export async function POST(request: NextRequest) {
  try {
    const authUserCookie = request.cookies.get('AuthUser');

    if (!authUserCookie?.value) {
      return NextResponse.json({ error: 'User not authenticated' }, { status: 401 });
    }

    let user;
    try {
      user = JSON.parse(authUserCookie.value) as { id: number; name?: string };
    } catch (error) {
      return NextResponse.json({ error: 'Invalid user session' }, { status: 401 });
    }

    const { data, error } = await supabase
      .from('push_subscriptions')
      .select('subscription')
      .eq('user_id', user.id);

    if (error) {
      console.error('Error fetching push subscriptions:', error);
      return NextResponse.json({ error: 'Failed to fetch subscriptions' }, { status: 500 });
    }

    if (!data || data.length === 0) {
      return NextResponse.json({ error: 'No push subscriptions found' }, { status: 404 });
    }

    const payload: SystemNotificationPayload = {
      type: 'system',
      title: 'Push notifications enabled',
      body: `Hi ${user?.name || 'there'}! Notifications are now active.`,
      url: '/chat',
      timestamp: new Date().toISOString(),
      priority: 'normal',
    };

    await Promise.all(
      data.map((row) =>
        sendPushNotification(row.subscription as any, payload).catch((err) => {
          console.error('Failed to send push notification:', err);
        })
      )
    );

    return NextResponse.json({ success: true });
  } catch (error) {
    console.error('Error sending test notification:', error);
    return NextResponse.json({ error: 'Server error' }, { status: 500 });
  }
}

