/**
 * GET /api/chapter-image/[domain]/[slug]/[n]
 * HEAD /api/chapter-image/[domain]/[slug]/[n]
 *
 * Proxies chapter illustration images from the Go backend.
 * HEAD returns 200/404 to check existence; GET returns the full image bytes.
 * Returns 404 when no image has been saved for this chapter.
 */

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

async function proxyChapterImage({ params, method }: { params: { domain: string; slug: string; n: string }; method: string }) {
	const { domain, slug, n } = params;

	let res: Response;
	try {
		res = await backendFetch(
			`/api/chapter-image/${encodeURIComponent(domain)}/${encodeURIComponent(slug)}/${encodeURIComponent(n)}`,
			{ method }
		);
	} catch {
		throw error(502, 'Could not reach backend');
	}

	if (res.status === 404) {
		throw error(404, 'No chapter image found');
	}
	if (!res.ok) {
		throw error(res.status, 'Could not fetch chapter image');
	}

	if (method === 'HEAD') {
		return new Response(null, {
			status: 200,
			headers: { 'Cache-Control': 'no-store' }
		});
	}

	const contentType = res.headers.get('content-type') ?? 'image/jpeg';
	const data = await res.arrayBuffer();

	return new Response(data, {
		status: 200,
		headers: {
			'Content-Type': contentType,
			'Cache-Control': 'public, max-age=31536000, immutable',
			'Content-Length': String(data.byteLength)
		}
	});
}

export const GET: RequestHandler = ({ params }) => proxyChapterImage({ params, method: 'GET' });
export const HEAD: RequestHandler = ({ params }) => proxyChapterImage({ params, method: 'HEAD' });
