/**
 * GET /api/v1/jobs — list recent indexing jobs.
 *
 * Query parameters:
 *   repositoryId  (optional) — filter by repository
 *   status        (optional) — filter by status: queued|running|done|failed
 *   limit         (optional, default 20, max 200)
 */

import { json } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { getClient } from '$lib/server/db/client.js';
import { JobQueue } from '$lib/server/pipeline/job-queue.js';
import { handleServiceError } from '$lib/server/utils/validation.js';
import type { IndexingJob } from '$lib/types';

export const GET: RequestHandler = ({ url }) => {
	try {
		const db = getClient();
		const queue = new JobQueue(db);

		const repositoryId = url.searchParams.get('repositoryId') ?? undefined;
		const status = (url.searchParams.get('status') ?? undefined) as
			| IndexingJob['status']
			| undefined;
		const limit = Math.min(parseInt(url.searchParams.get('limit') ?? '20', 10) || 20, 200);

		const jobs = queue.listJobs({ repositoryId, status, limit });
		const total = queue.countJobs({ repositoryId, status });

		return json({ jobs, total });
	} catch (err) {
		return handleServiceError(err);
	}
};

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