import { Metadata } from "next";
import CourseDetail from "./CourseClient";
import { generatePageMetadata } from "@/utils/generatePageMetadata";
import { getApiBaseUrl } from "@/components/main/BaseUrl";
import { buildCourseDetailSeo } from "@/lib/buildCourseDetailSeo";
import { getServerLanguage } from "@/lib/i18n/server";
import { translateCommon } from "@/lib/i18n/translate";

type Props = {
  params: Promise<{ id: string; title: string }>;
};

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { id, title: slugTitle } = await params;

  try {
    const res = await fetch(
      `${getApiBaseUrl()}/academy/academy/get/curses?page=1&limit=20&status=accept&_id=${id}`,
      { cache: "no-store" }
    );

    const response = await res.json();
    const course =
      response?.data?.courses?.[0] ||
      response?.courses?.[0] ||
      response?.[0];

    if (course) {
      const lang = await getServerLanguage();
      const seo = buildCourseDetailSeo(course, id, lang);

      return generatePageMetadata({
        title: seo.title,
        description: seo.description,
        path: seo.path,
        type: "article",
        lang,
      });
    }
  } catch (error) {
    console.error("خطا در دریافت اطلاعات سئو:", error);
  }

  const lang = await getServerLanguage();

  return generatePageMetadata({
    title: translateCommon(lang, "academy.course.metaTitle"),
    description: translateCommon(lang, "academy.course.metaDescription"),
    path: `/academy/${id}/${encodeURIComponent(slugTitle || "course")}`,
    lang,
  });
}

export default async function CoursePage({ params }: Props) {
  const { id } = await params;
  return <CourseDetail courseId={id} />;
}
