/**
 * GET  /api/v1/libs  — list all repositories
 * POST /api/v1/libs  — add a new 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 } from '$lib/server/utils/validation';

function getService() {
	return new RepositoryService(getClient());
}

export const GET: RequestHandler = ({ url }) => {
	try {
		const service = getService();
		const state = url.searchParams.get('state') as
			| 'pending'
			| 'indexing'
			| 'indexed'
			| 'error'
			| undefined;
		const limit = Math.min(parseInt(url.searchParams.get('limit') ?? '50'), 200);
		const offset = parseInt(url.searchParams.get('offset') ?? '0');

		const libraries = service.list({ state: state ?? undefined, limit, offset });
		const total = service.count(state ?? undefined);

		// Augment each library with its versions array; strip sensitive fields.
		const enriched = libraries.map(({ githubToken: _token, ...repo }) => ({
			...repo,
			versions: service.getVersions(repo.id)
		}));

		return json({ libraries: enriched, total, limit, offset });
	} catch (err) {
		return handleServiceError(err);
	}
};

export const POST: RequestHandler = async ({ request }) => {
	try {
		const body = await request.json();
		const service = getService();

		const repo = service.add({
			source: body.source,
			sourceUrl: body.sourceUrl,
			title: body.title,
			description: body.description,
			branch: body.branch,
			githubToken: body.githubToken
		});

		let jobResponse: { id: string; status: string } | null = null;
		if (body.autoIndex !== false) {
			const queue = getQueue();
			const job = queue
				? queue.enqueue(repo.id)
				: service.createIndexingJob(repo.id);
			jobResponse = { id: job.id, status: job.status };
		}

		const { githubToken: _token, ...safeRepo } = repo;
		return json(
			{ library: safeRepo, ...(jobResponse ? { job: jobResponse } : {}) },
			{ status: 201 }
		);
	} catch (err) {
		return handleServiceError(err);
	}
};

export const OPTIONS: RequestHandler = () => {
	return new Response(null, {
		status: 204,
		headers: corsHeaders()
	});
};

function corsHeaders(): Record<string, string> {
	return {
		'Access-Control-Allow-Origin': '*',
		'Access-Control-Allow-Methods': 'GET, POST, PATCH, DELETE, OPTIONS',
		'Access-Control-Allow-Headers': 'Content-Type, Authorization'
	};
}
