/**
 * SvelteKit server hooks (TRUEREF-0009).
 *
 * Runs once when the Node.js server process starts. Initialises the database
 * and kicks off the indexing pipeline + job queue so queued jobs resume
 * automatically after a restart.
 */

import { initializeDatabase } from '$lib/server/db/index.js';
import { getClient } from '$lib/server/db/client.js';
import { initializePipeline } from '$lib/server/pipeline/startup.js';
import { EMBEDDING_CONFIG_KEY, createProviderFromConfig, defaultEmbeddingConfig } from '$lib/server/embeddings/factory.js';
import { EmbeddingService } from '$lib/server/embeddings/embedding.service.js';
import type { EmbeddingConfig } from '$lib/server/embeddings/factory.js';
import type { Handle } from '@sveltejs/kit';

// ---------------------------------------------------------------------------
// Server initialisation — runs once on startup
// ---------------------------------------------------------------------------

try {
	initializeDatabase();

	const db = getClient();

	// Load persisted embedding configuration (if any).
	const configRow = db
		.prepare<[string], { value: string }>(`SELECT value FROM settings WHERE key = ?`)
		.get(EMBEDDING_CONFIG_KEY);

	let embeddingService: EmbeddingService | null = null;

	if (configRow) {
		try {
			const config: EmbeddingConfig =
				typeof configRow.value === 'string'
					? JSON.parse(configRow.value)
					: (configRow.value as EmbeddingConfig);

			if (config.provider !== 'none') {
				const provider = createProviderFromConfig(config);
				embeddingService = new EmbeddingService(db, provider);
			}
		} catch (err) {
			console.warn(
				`[hooks.server] Could not load embedding config: ${err instanceof Error ? err.message : String(err)}`
			);
		}
	} else {
		// Use the default (noop) config so the pipeline is still wired up.
		const config = defaultEmbeddingConfig();
		if (config.provider !== 'none') {
			const provider = createProviderFromConfig(config);
			embeddingService = new EmbeddingService(db, provider);
		}
	}

	initializePipeline(db, embeddingService);
	console.log('[hooks.server] Indexing pipeline initialised.');
} catch (err) {
	console.error(
		`[hooks.server] Failed to initialise server: ${err instanceof Error ? err.message : String(err)}`
	);
}

// ---------------------------------------------------------------------------
// CORS headers applied to all /api/* responses
// ---------------------------------------------------------------------------

const CORS_HEADERS = {
	'Access-Control-Allow-Origin': '*',
	'Access-Control-Allow-Methods': 'GET, POST, PATCH, DELETE, OPTIONS',
	'Access-Control-Allow-Headers': 'Content-Type, Authorization'
} as const;

// ---------------------------------------------------------------------------
// Request handler — CORS + pass-through
// ---------------------------------------------------------------------------

export const handle: Handle = async ({ event, resolve }) => {
	const { pathname } = event.url;

	// Handle CORS pre-flight for all API routes.
	if (event.request.method === 'OPTIONS' && pathname.startsWith('/api/')) {
		return new Response(null, {
			status: 204,
			headers: CORS_HEADERS
		});
	}

	const response = await resolve(event);

	// Attach CORS headers to all API responses.
	if (pathname.startsWith('/api/')) {
		for (const [key, value] of Object.entries(CORS_HEADERS)) {
			response.headers.set(key, value);
		}
	}

	return response;
};
