import type { Metadata } from "next";
import { notFound } from "next/navigation";
import { getAllPosts, getPostBySlug } from "@/lib/blog";
import BlogPost from "@/components/BlogPost";

// Force SSR - always fetch fresh data
export const dynamic = 'force-dynamic';

// Generate static params for all blog posts
export async function generateStaticParams() {
  const posts = await getAllPosts();
  return posts.map((post) => ({
    slug: post.slug,
  }));
}

// Generate metadata for each post
export async function generateMetadata({ params }: { params: Promise<{ slug: string }> }): Promise<Metadata> {
  const { slug } = await params;
  const post = await getPostBySlug(slug);

  if (!post) {
    return {
      title: "Post nie znaleziony — SZMYT AI Labs",
    };
  }

  return {
    title: post.seo?.title || `${post.title}`,
    description: post.seo?.description || post.excerpt,
    keywords: post.seo?.keywords || (Array.isArray(post.tags) ? post.tags : [post.tags]),
    openGraph: {
      title: post.seo?.title || post.title,
      description: post.seo?.description || post.excerpt,
      url: `https://aiagentdlafirm.pl/blog/${post.slug}/`,
      type: "article",
      publishedTime: post.publishedAt.toISOString(),
      modifiedTime: post.updatedAt.toISOString(),
      authors: post.author,
      images: post.coverImage ? [{ url: post.coverImage }] : [],
    },
    alternates: { canonical: `https://aiagentdlafirm.pl/blog/${post.slug}/` },
  };
}

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

  if (!post) {
    notFound();
  }

  const articleSchema = {
    "@context": "https://schema.org",
    "@type": post.category === "case-study" ? "Case Study" : "BlogPosting",
    headline: post.title,
    description: post.excerpt,
    image: post.coverImage,
    datePublished: post.publishedAt.toISOString(),
    dateModified: post.updatedAt.toISOString(),
    author: {
      "@type": "Person",
      name: post.author,
    },
    publisher: {
      "@type": "Organization",
      name: "SZMYT AI Labs",
      url: "https://aiagentdlafirm.pl",
    },
    mainEntityOfPage: {
      "@type": "WebPage",
      "@id": `https://aiagentdlafirm.pl/blog/${post.slug}/`,
    },
    keywords: Array.isArray(post.tags) ? post.tags.join(", ") : post.tags,
    breadcrumb: {
      "@type": "BreadcrumbList",
      itemListElement: [
        { "@type": "ListItem", position: 1, name: "Strona główna", item: "https://aiagentdlafirm.pl/" },
        { "@type": "ListItem", position: 2, name: "Blog", item: "https://aiagentdlafirm.pl/blog/" },
        { "@type": "ListItem", position: 3, name: post.title, item: `https://aiagentdlafirm.pl/blog/${post.slug}/` },
      ],
    },
  };

  return (
    <>
      <script type="application/ld+json" dangerouslySetInnerHTML={{ __html: JSON.stringify(articleSchema) }} />
      <BlogPost post={post} />
    </>
  );
}
