import { getDictionary } from "@/get-dictionary";
import type { Locale } from "@/i18n-config";
import AdminClient from "@/components/AdminClient";
import { getProjects, getBlogPosts, getAdminSession, getPartners } from "@/app/actions";
import { redirect } from "next/navigation";

export async function generateStaticParams() {
  return [{ lang: "tr" }, { lang: "en" }];
}

export async function generateMetadata() {
  return {
    title: "Yönetim Paneli | Ayris Tech",
    description: "Ayris Tech sistem, proje ve site ayarları yönetim merkezi.",
  };
}

export default async function AdminPage({ params }: { params: Promise<{ lang: Locale }> }) {
  const { lang } = await params;
  
  // Guard dashboard route against unauthenticated users
  const session = await getAdminSession();
  if (!session) {
    redirect(`/${lang}/admin/login`);
  }

  const dict = await getDictionary(lang);

  const initialDbProjects = await getProjects();
  const initialDbBlogPosts = await getBlogPosts();
  const initialDbPartners = await getPartners();

  // Convert DB format to expected BlogPost format
  const initialBlogPosts = initialDbBlogPosts.map((dbPost) => ({
    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,
    }
  }));

  // Convert DB Project format to standard ProjectData format (mapping fields properly)
  const initialProjects = initialDbProjects.map((p) => ({
    id: p.id,
    num: p.num,
    slug: p.slug,
    title: p.title,
    tag: p.tag,
    desc: p.desc,
    spec: p.spec,
    year: p.year,
    client: p.client,
    duration: p.duration,
    tech: p.tech,
    challenge: p.challenge,
    solution: p.solution,
    results: p.results,
    image: p.image,
    gallery: p.gallery,
    website: p.website,
  }));

  // Map database Partners
  const initialPartners = initialDbPartners.map((p) => ({
    id: p.id,
    name: p.name,
    tag: p.tag,
    mono: p.mono,
    year: p.year,
    desc: p.desc,
  }));

  return (
    <AdminClient
      lang={lang}
      dict={dict}
      initialProjects={initialProjects}
      initialBlogPosts={initialBlogPosts}
      initialPartners={initialPartners}
    />
  );
}
