/**
 * Push Notification Subscription API
 * 
 * Handles web push notification subscription/unsubscription
 * for queue processing updates.
 */

import { json } from '@sveltejs/kit';
import { pushNotificationService } from '$lib/server/notifications/PushNotificationService.js';
import type { RequestHandler } from './$types.js';

/**
 * Subscribe to push notifications
 * 
 * POST /api/notifications/subscribe
 * 
 * Body:
 * {
 *   "subscription": {
 *     "endpoint": "https://...",
 *     "keys": {
 *       "p256dh": "...",
 *       "auth": "..."
 *     }
 *   },
 *   "clientId": "unique-client-id"
 * }
 */
export const POST: RequestHandler = async ({ request }) => {
  try {
    const { subscription, clientId } = await request.json();
    
    // Validate required fields
    if (!subscription || !subscription.endpoint || !subscription.keys) {
      return json(
        { error: 'Invalid subscription object' },
        { status: 400 }
      );
    }
    
    if (!clientId || typeof clientId !== 'string') {
      return json(
        { error: 'Client ID is required' },
        { status: 400 }
      );
    }
    
    // Subscribe client
    await pushNotificationService.subscribe(clientId, {
      endpoint: subscription.endpoint,
      keys: {
        p256dh: subscription.keys.p256dh,
        auth: subscription.keys.auth
      }
    });
    
    console.log(`[NotificationAPI] Client ${clientId} subscribed to push notifications`);
    
    return json({
      success: true,
      message: 'Successfully subscribed to push notifications',
      subscriptionCount: pushNotificationService.getSubscriptionCount()
    });
    
  } catch (error) {
    console.error('[NotificationAPI] Subscription error:', error);
    return json(
      { error: 'Failed to subscribe to notifications' },
      { status: 500 }
    );
  }
};

/**
 * Unsubscribe from push notifications
 * 
 * DELETE /api/notifications/subscribe
 * 
 * Body:
 * {
 *   "clientId": "unique-client-id"
 * }
 */
export const DELETE: RequestHandler = async ({ request }) => {
  try {
    const { clientId } = await request.json();
    
    if (!clientId || typeof clientId !== 'string') {
      return json(
        { error: 'Client ID is required' },
        { status: 400 }
      );
    }
    
    // Unsubscribe client
    await pushNotificationService.unsubscribe(clientId);
    
    console.log(`[NotificationAPI] Client ${clientId} unsubscribed from push notifications`);
    
    return json({
      success: true,
      message: 'Successfully unsubscribed from push notifications',
      subscriptionCount: pushNotificationService.getSubscriptionCount()
    });
    
  } catch (error) {
    console.error('[NotificationAPI] Unsubscription error:', error);
    return json(
      { error: 'Failed to unsubscribe from notifications' },
      { status: 500 }
    );
  }
};