import { BASE_URL, IMAGE_BASE_URL } from "@/components/main/BaseUrl";
import AdvertisingProfileContent from "@/components/billboards/AdvertisingProfileContent";
import BillboardAdNotFound from "@/components/billboards/BillboardAdNotFound";
import { IAdvertisingProfile } from "@/types/types";
import { Metadata } from "next";
import { cache } from "react";
import { getLocaleBundle } from "@/lib/i18n/resources";
import { getServerLanguage } from "@/lib/i18n/server";

interface IUserProps {
  params: Promise<{ id: string[] }>;
}

const getProfile = cache(async (id: string) => {
  try {
    const res = await fetch(`${BASE_URL}/advertising/profile-web?vitrineId=${id}`, {
      cache: "no-store",
    });
    if (!res.ok) return null;
    const data = await res.json();
    return data.profileDetails as IAdvertisingProfile;
  } catch {
    return null;
  }
});

export async function generateMetadata({ params }: IUserProps): Promise<Metadata> {
  const { id: idSegments } = await params;
  const id = idSegments?.[0] || "";
  const lang = await getServerLanguage();
  const common = getLocaleBundle(lang).common as {
    billboards: { adNotFoundMeta: string };
  };
  const profile = await getProfile(id);

  if (!profile) {
    return { title: common.billboards.adNotFoundMeta };
  }

  const titleParts = [
    profile.vitrine_name,
    profile.category,
    profile.neighbourhood,
    profile.city?.name,
    "Modstagram",
  ].filter(Boolean);

  const finalTitle = titleParts.join(" - ");
  const description = `${profile.category || ""} - ${profile.city?.name || ""} - ${profile.about_us || ""}`.slice(0, 160);
  const image = profile.allImages?.[0]
    ? `${IMAGE_BASE_URL}${profile.allImages[0]}`
    : "/images/logo.png";

  return {
    title: finalTitle,
    description,
    openGraph: {
      title: finalTitle,
      description,
      url: `https://modstagram.com/billboards/${id}`,
      siteName: "Modstagram",
      images: [{ url: image }],
      locale: lang === "fa" ? "fa_IR" : "en_US",
      type: "article",
    },
    alternates: {
      canonical: `https://modstagram.com/billboards/${id}`,
    },
  };
}

export default async function AdvertisingProfilePage({ params }: IUserProps) {
  const { id: idSegments } = await params;
  const id = idSegments?.[0] || "";
  const profile = await getProfile(id);

  if (!profile) return <BillboardAdNotFound />;

  return <AdvertisingProfileContent profile={profile} id={id} />;
}
