/**
 * Dynamic OG image for /retete/{slug}
 * GET /api/og/recipe/{slug}.png → 1200×630 PNG
 */
import type { APIRoute } from 'astro';
import { RECIPES_BY_SLUG } from '../../../../lib/recipes.js';
import { ogRecipeImage } from '../../../../lib/og-image.js';

export const prerender = false;

export const GET: APIRoute = async ({ params }) => {
  const slug = params.slug as string;
  const recipe = RECIPES_BY_SLUG[slug];

  if (!recipe) {
    return new Response('Recipe not found', { status: 404 });
  }

  try {
    const rows = await recipe.fetch();
    const top = rows[0];
    const png = await ogRecipeImage({
      title: recipe.title,
      count: rows.length,
      primaryRow: top ? {
        name: top.primary,
        metric: top.metric,
        tone: top.badge?.tone,
      } : undefined,
    });

    return new Response(png as any, {
      status: 200,
      headers: {
        'Content-Type': 'image/png',
        'Cache-Control': 'public, max-age=3600, s-maxage=86400',
      },
    });
  } catch (err: any) {
    console.error('[OG recipe]', err);
    return new Response('Render error', { status: 500 });
  }
};
