import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { presignVoiceSample } from '$lib/server/minio';
import { log } from '$lib/server/logger';
import * as cache from '$lib/server/presignCache';

/**
 * GET /api/presign/voice-sample?voice=af_bella
 * Returns a presigned URL for the voice sample audio file.
 *
 * The backend generates the sample on demand via Kokoro TTS if it does not
 * exist yet, so this endpoint always returns 200 { url } (or 5xx on failure).
 *
 * Results are cached in-process for 50 minutes to avoid a backend + MinIO
 * round-trip on every voice-selection preview play.
 */
export const GET: RequestHandler = async ({ url }) => {
	const voice = url.searchParams.get('voice');
	if (!voice) {
		error(400, 'Missing voice parameter');
	}

	const cacheKey = cache.sampleKey(voice);

	// Fast path: return cached URL if still valid.
	const cached = await cache.get(cacheKey);
	if (cached) {
		return json({ url: cached });
	}

	// Slow path: call backend → generate if needed → MinIO presign.
	try {
		const presignedUrl = await presignVoiceSample(voice);
		await cache.set(cacheKey, presignedUrl);
		return json({ url: presignedUrl });
	} catch (e) {
		log.error('presign', 'presign voice sample failed', { voice, err: String(e) });
		error(502, `Failed to presign voice sample: ${e}`);
	}
};
