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

/** @param {Request} request @param {{ ASSETS?: { fetch(input: RequestInfo, init?: RequestInit): Promise<Response> } }} env */
export async function handleRandomGet(request, env) {
  const url = new URL(request.url);
  const format = (url.searchParams.get('format') || 'redirect').toLowerCase();
  const manifest = await loadManifest(request, env);
  const variant = detectVariant(request);
  const { folder, images } = getVariantPayload(manifest, variant);

  if (!images.length) {
    return Response.json(
      { error: 'no images available', variant, folder },
      { status: 404, headers: { 'Cache-Control': 'no-store, max-age=0', 'Access-Control-Allow-Origin': '*' } },
    );
  }

  const filename = pickRandom(images);
  const assetUrl = buildAssetUrl(request, folder, filename);

  if (format === 'json') {
    return Response.json(
      { variant, folder, filename, url: assetUrl, count: images.length },
      { headers: { 'Cache-Control': 'no-store, max-age=0', 'Access-Control-Allow-Origin': '*' } },
    );
  }

  return new Response(null, {
    status: 302,
    headers: {
      Location: assetUrl,
      'Cache-Control': 'no-store, max-age=0',
      'Access-Control-Allow-Origin': '*',
    },
  });
}
