import { ImageResponse } from 'next/og';
import { getPostBySlug } from '@/lib/blog';
import { OGImageTemplate } from '@/components/OGImageTemplate';
import { getOgFonts, OG_IMAGE_SIZE } from '@/lib/og-helper';
import { SITE_URL } from '@/lib/schema';

export const runtime = 'nodejs';

export default async function Image({
  params,
}: {
  params: Promise<{ locale: string; slug: string }>;
}) {
  const { locale, slug } = await params;
  const post = await getPostBySlug(slug, locale);

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

  const fonts = await getOgFonts();

  // We don't have request.url here, but we can assume the domain from SITE_URL or config
  // For local images during dev, relative paths in <img> might not work in Satori
  // but if we are in nodejs runtime, we could potentially read from disk.
  // For now, let's just make sure it's absolute.
  const featuredImage = post.frontmatter.featuredImage
    ? post.frontmatter.featuredImage.startsWith('http')
      ? post.frontmatter.featuredImage
      : `${SITE_URL}${post.frontmatter.featuredImage}`
    : undefined;

  return new ImageResponse(
    <OGImageTemplate
      title={post.frontmatter.title}
      description={post.frontmatter.excerpt}
      label={post.frontmatter.category || 'Blog'}
      image={featuredImage}
    />,
    {
      ...OG_IMAGE_SIZE,
      fonts,
    },
  );
}
