/**
 * POST /api/v1/libs/:id/index  — trigger an indexing job for a repository.
 */
import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { getClient } from '$lib/server/db/client';
import { RepositoryService } from '$lib/server/services/repository.service';
import { getQueue } from '$lib/server/pipeline/startup';
import { handleServiceError, NotFoundError } from '$lib/server/utils/validation';

export const POST: RequestHandler = async ({ params, request }) => {
	try {
		const service = new RepositoryService(getClient());
		const id = decodeURIComponent(params.id);

		const repo = service.get(id);
		if (!repo) throw new NotFoundError(`Repository ${id} not found`);

		let versionId: string | undefined;
		try {
			const body = await request.json();
			versionId = body.version ?? undefined;
		} catch {
			// body is optional
		}

		// Use the queue so processNext() is triggered immediately.
		// Falls back to direct DB insert if the queue isn't initialised yet.
		const queue = getQueue();
		const job = queue
			? queue.enqueue(id, versionId)
			: service.createIndexingJob(id, versionId);

		return json({ job }, { status: 202 });
	} catch (err) {
		return handleServiceError(err);
	}
};

export const OPTIONS: RequestHandler = () => {
	return new Response(null, {
		status: 204,
		headers: {
			'Access-Control-Allow-Origin': '*',
			'Access-Control-Allow-Methods': 'POST, OPTIONS',
			'Access-Control-Allow-Headers': 'Content-Type, Authorization'
		}
	});
};
