/**
 * Health Check API Endpoint
 *
 * Provides status information about critical application services:
 * - Queue processing status
 * - Queue statistics (pending, in_progress, etc.)
 * - Server uptime information
 *
 * Used for monitoring and debugging queue processor functionality.
 */

import { json } from '@sveltejs/kit';
import { queueManager } from '$lib/server/queue/QueueManager';
import { queueProcessor } from '$lib/server/queue/QueueProcessor';

export const GET = async () => {
	try {
		// Get current queue items by status
		const allItems = queueManager.getAll();
		const statusCounts = {
			pending: allItems.filter((item) => item.status === 'pending').length,
			in_progress: allItems.filter((item) => item.status === 'in_progress').length,
			success: allItems.filter((item) => item.status === 'success').length,
			error: allItems.filter((item) => item.status === 'error').length,
			unhealthy: allItems.filter((item) => item.status === 'unhealthy').length
		};

		const stats = {
			total: allItems.length
		};

		const healthData = {
			timestamp: new Date().toISOString(),
			status: 'healthy',
			services: {
				queueProcessor: {
					status: 'running', // QueueProcessor auto-starts, so it's always running
					description: 'Queue processing service is operational'
				},
				queueManager: {
					status: 'healthy',
					stats,
					statusCounts
				}
			},
			uptime: process.uptime(),
			version: process.env.npm_package_version || 'unknown'
		};

		return json(healthData);
	} catch (error) {
		console.error('[Health Check] Error retrieving health status:', error);

		return json(
			{
				timestamp: new Date().toISOString(),
				status: 'unhealthy',
				error: error instanceof Error ? error.message : 'Unknown error',
				uptime: process.uptime()
			},
			{ status: 500 }
		);
	}
};
