import { redirect } from '@sveltejs/kit';
import type { PageServerLoad } from './$types';
import { listScrapingTasks } from '$lib/server/pocketbase';
import { log } from '$lib/server/logger';
import { backendFetch } from '$lib/server/scraper';

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

	const [tasks, statusRes] = await Promise.all([
		listScrapingTasks().catch((e) => {
			log.warn('admin/scrape', 'failed to load tasks', { err: String(e) });
			return [];
		}),
		backendFetch('/api/scrape/status').catch(() => null)
	]);

	let running = false;
	if (statusRes?.ok) {
		const body = await statusRes.json().catch(() => null);
		running = body?.running ?? false;
	}

	return { tasks, running };
};
