import { getDictionary } from "@/get-dictionary";
import type { Locale } from "@/i18n-config";
import { getBlogPosts } from "@/app/actions";
import BlogDetailClient from "@/components/BlogDetailClient";
import { notFound } from "next/navigation";

// Convert DB format to expected BlogPost format
function mapBlogPost(dbPost: any) {
  return {
    id: dbPost.id,
    slug: dbPost.slug,
    date: dbPost.date,
    author: dbPost.author,
    authorRole: dbPost.authorRole,
    image: dbPost.image,
    tr: {
      title: dbPost.trTitle,
      excerpt: dbPost.trExcerpt,
      readingTime: dbPost.trReadingTime,
      category: dbPost.trCategory,
      tags: dbPost.trTags,
      content: dbPost.trContent,
    },
    en: {
      title: dbPost.enTitle,
      excerpt: dbPost.enExcerpt,
      readingTime: dbPost.enReadingTime,
      category: dbPost.enCategory,
      tags: dbPost.enTags,
      content: dbPost.enContent,
    }
  };
}

export async function generateStaticParams() {
  const langs: Locale[] = ["en", "tr"];
  const dbPosts = await getBlogPosts();
  
  const slugs = dbPosts.length > 0
    ? dbPosts.map((p) => p.slug)
    : [
        "real-time-anomaly-detection-ai",
        "web3-consortium-networks-logistics",
        "headless-ecommerce-conversion-rates",
      ];

  return langs.flatMap((lang) =>
    slugs.map((slug) => ({ lang, slug }))
  );
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ lang: Locale; slug: string }>;
}) {
  const { lang, slug } = await params;
  const dbPosts = await getBlogPosts();
  
  const dbPost = dbPosts.find((p) => p.slug === slug);
  if (!dbPost) return { title: "Not Found" };

  const post = mapBlogPost(dbPost);
  const content = post[lang] || post.en;
  return {
    title: `${content.title} | Ayris Tech`,
    description: content.excerpt,
  };
}

export default async function BlogPostPage({
  params,
}: {
  params: Promise<{ lang: Locale; slug: string }>;
}) {
  const { lang, slug } = await params;
  const dict = await getDictionary(lang);
  
  const dbPosts = await getBlogPosts();
  const dbPost = dbPosts.find((p) => p.slug === slug);

  if (!dbPost) notFound();

  const post = mapBlogPost(dbPost);

  return <BlogDetailClient lang={lang} dict={dict} post={post} />;
}
