/**
 * Test Push Notification API
 *
 * Allows manual testing of push notifications with different payloads.
 * Sends notification to all subscribed clients.
 */

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

/**
 * Send test push notification
 *
 * POST /api/notifications/test
 *
 * Body:
 * {
 *   "type": "success" | "error" | "progress"
 * }
 */
export const POST: RequestHandler = async ({ request }) => {
	try {
		const { type } = await request.json();

		if (!type || !['success', 'error', 'progress'].includes(type)) {
			return json(
				{ error: 'Invalid notification type. Must be: success, error, or progress' },
				{ status: 400 }
			);
		}

		const testItemId = 'test_' + Date.now();

		// Create test payloads for each type
		const payloads = {
			success: {
				type: 'success' as const,
				itemId: testItemId,
				body: 'Test recipe extraction completed successfully!',
				recipeName: 'Test Recipe',
				tag: `recipe-success-${testItemId}`,
				requireInteraction: false
			},
			error: {
				type: 'error' as const,
				itemId: testItemId,
				body: 'Test recipe extraction failed - this is a test error',
				tag: `recipe-error-${testItemId}`,
				requireInteraction: true
			},
			progress: {
				type: 'progress' as const,
				itemId: testItemId,
				body: 'Test recipe extraction in progress: parsing phase',
				tag: `recipe-progress-${testItemId}`,
				requireInteraction: false
			}
		};

		const payload = payloads[type as keyof typeof payloads];

		await pushNotificationService.sendNotification(payload);

		console.log(`[NotificationTestAPI] Sent test ${type} notification`);

		return json({
			success: true,
			message: `Test ${type} notification sent`,
			subscriberCount: pushNotificationService.getSubscriptionCount()
		});
	} catch (error) {
		console.error(
			'[NotificationTestAPI] Error sending test notification:',
			error instanceof Error ? error.message : String(error)
		);
		return json({ error: 'Failed to send test notification' }, { status: 500 });
	}
};
