import { json, error } from '@sveltejs/kit';
import type { RequestHandler } from './$types';
import { backendFetch } from '$lib/server/scraper';

/**
 * GET /api/admin/import
 * List all import tasks.
 */
export const GET: RequestHandler = async ({ locals }) => {
	if (!locals.user || locals.user.role !== 'admin') {
		throw error(403, 'Forbidden');
	}
	const res = await backendFetch('/api/admin/import', { method: 'GET' });
	const data = await res.json().catch(() => ({ tasks: [] }));
	return json(data);
};

/**
 * POST /api/admin/import
 * Create a new import task. Supports both multipart/form-data (file upload)
 * and application/json (object key reference).
 */
export const POST: RequestHandler = async ({ request, locals }) => {
	if (!locals.user || locals.user.role !== 'admin') {
		throw error(403, 'Forbidden');
	}

	const ct = request.headers.get('content-type') ?? '';

	let res: Response;

	if (ct.includes('multipart/form-data')) {
		// Forward the raw FormData body; let the browser-set Content-Type
		// (which includes the boundary) pass through unchanged.
		const formData = await request.formData();
		res = await backendFetch('/api/admin/import', {
			method: 'POST',
			// Do NOT set Content-Type manually — the fetch API sets it
			// automatically with the correct boundary when given a FormData body.
			body: formData
		});
	} else {
		const body = await request.json();
		res = await backendFetch('/api/admin/import', {
			method: 'POST',
			headers: { 'Content-Type': 'application/json' },
			body: JSON.stringify(body)
		});
	}

	if (!res.ok) {
		const err = await res.json().catch(() => ({ error: 'Failed to create import task' }));
		throw error(res.status, err.error || 'Failed to create import task');
	}
	const data = await res.json();
	return json(data);
};
