import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
import { listAudioJobs, type AudioCacheEntry, type AudioJob } from '$lib/server/pocketbase';
import { log } from '$lib/server/logger';

export const load: PageServerLoad = async ({ locals }) => {
	if (locals.user?.role !== 'admin') {
		redirect(302, '/');
	}

	const jobs = await listAudioJobs().catch((e): AudioJob[] => {
		log.warn('admin/audio', 'failed to load audio jobs', { err: String(e) });
		return [];
	});

	// Derive cache entries from done jobs — no second query needed.
	const entries: AudioCacheEntry[] = jobs
		.filter((j) => j.status === 'done')
		.map((j) => ({
			id: j.id,
			cache_key: j.cache_key,
			filename: `${j.cache_key}.mp3`,
			updated: j.finished
		}));

	return { entries, jobs };
};
