/**
 * POST /api/v1/libs/:id/versions/:tag/index — queue an indexing job for a specific version
 */

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 { VersionService } from '$lib/server/services/version.service';
import { getQueue } from '$lib/server/pipeline/startup';
import { handleServiceError, NotFoundError } from '$lib/server/utils/validation';

function getServices() {
	const db = getClient();
	return {
		repoService: new RepositoryService(db),
		versionService: new VersionService(db)
	};
}

// ---------------------------------------------------------------------------
// POST /api/v1/libs/:id/versions/:tag/index
// ---------------------------------------------------------------------------

export const POST: RequestHandler = ({ params }) => {
	try {
		const { repoService, versionService } = getServices();
		const repositoryId = decodeURIComponent(params.id);
		const tag = decodeURIComponent(params.tag);

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

		const version = versionService.getByTag(repositoryId, tag);
		if (!version) {
			throw new NotFoundError(`Version ${tag} not found for repository ${repositoryId}`);
		}

		const queue = getQueue();
		const job = queue
			? queue.enqueue(repositoryId, version.id)
			: repoService.createIndexingJob(repositoryId, version.id);
		return json({ job }, { status: 202 });
	} catch (err) {
		return handleServiceError(err);
	}
};

// ---------------------------------------------------------------------------
// OPTIONS preflight
// ---------------------------------------------------------------------------

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'
		}
	});
};
