import { getVariantPayload, loadManifest } from '../lib/background.js';

/** @param {Request} request @param {{ ASSETS?: { fetch(input: RequestInfo, init?: RequestInit): Promise<Response> } }} env */
export async function handleListGet(request, env) {
  const manifest = await loadManifest(request, env);

  return Response.json(
    {
      generated_at: manifest?.generated_at || null,
      variants: {
        mobile: summarizeVariant(manifest, 'mobile'),
        desktop: summarizeVariant(manifest, 'desktop'),
      },
    },
    { headers: { 'Cache-Control': 'no-store, max-age=0', 'Access-Control-Allow-Origin': '*' } },
  );
}

/** @param {unknown} manifest @param {'mobile' | 'desktop'} variant */
function summarizeVariant(manifest, variant) {
  const { folder, images } = getVariantPayload(manifest, variant);
  return { folder, count: images.length, images };
}
