import servicesData from "@/data/services.json";
import { metaObject } from "@/config/site.config";
import { routing } from "@/i18n/routing";
import ServicePage from "@/app/pages/service";
import { notFound } from "next/navigation";

const services = servicesData?.services ?? [];

type RouteParams = Promise<{
  lang: string;
  slug: string;
}>;

const getLocalizedValue = (lang: string, en?: string, ar?: string): string => {
  if (lang === "ar") {
    return ar ?? en ?? "";
  }
  return en ?? ar ?? "";
};

const getServiceContent = (slug: string | undefined) =>
  services.find((item) => item.slug === slug);

export async function generateStaticParams() {
  const slugs = services.map((service) => service.slug);

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

export async function generateMetadata({ params }: { params: RouteParams }) {
  const { lang, slug } = await params;
  const service = getServiceContent(slug);

  if (!service) {
    return metaObject("Services", "Service details");
  }

  const title = getLocalizedValue(
    lang,
    service?.seo?.meta_title_en,
    service?.seo?.meta_title_ar
  );

  const description = getLocalizedValue(
    lang,
    service?.seo?.meta_description_en,
    service?.seo?.meta_description_ar
  );

  return metaObject(
    title || "Service",
    description || "Detailed information about this service.",
    undefined,
    service?.seo?.og_image,
    `/services/${slug}`
  );
}

export default async function ServiceDetailsPage({ params }: { params: RouteParams }) {
  const { lang, slug } = await params;

  const service = getServiceContent(slug);

  if (!service) {
    notFound();
  }

  return <ServicePage slug={slug} lang={lang} initialService={service} />;
}
