import { getImageUrl } from "@/utils/imageHelper";
import DesignHouseDeails from "./DesignHouseDeails";
import { APPLE_ICON, OG_BANNER } from "@/utils/staticValues";
import { Metadata } from "next";

// Helper function to fetch design house data with caching
async function fetchDesignHouseData(slug: string) {
  const siteUrl = process.env.NEXT_PUBLIC_SITE_URL || "http://localhost:3000";
  const res = await fetch(`${siteUrl}/api/design-houses/${slug}`, {
    // Enable caching for this request
    next: { revalidate: 300 } // Cache for 5 minutes
  });
  
  if (!res.ok) {
    throw new Error(`Failed to fetch design house data: ${res.status}`);
  }
  
  return await res.json();
}

export async function generateMetadata({
  params,
}: {
  params: Promise<{ slug: string }>;
}): Promise<Metadata> {
  const { slug } = await params;
  const data = await fetchDesignHouseData(slug);
  const dh = data.data.design_house;

  const facebookBioImage = dh.facebook || dh.bio_image || "";
  // Use getImageUrl to ensure the image URL is properly formatted
  const fbOGBanner = getImageUrl(facebookBioImage) || OG_BANNER;

  const xBioImage = dh.x || dh.bio_image || "";
  // Use getImageUrl to ensure the image URL is properly formatted
  const xBanner = getImageUrl(xBioImage) || OG_BANNER;

  const designHouseSeoTitle = `${dh.name} - Design House | Morni`;


  return {
    title: designHouseSeoTitle,
    description:
      dh.bio || `Discover ${dh.name}'s unique designs and creations on Morni`,
    openGraph: {
      title: designHouseSeoTitle,
      description:
        dh.bio || `Discover ${dh.name}'s unique designs and creations on Morni`,
      images: [
        {
          url: fbOGBanner,
          width: 1200,
          height: 630,
          alt: `${dh.name} - Design House`,
        },
      ],
    },
    twitter: {
      card: "summary_large_image",
      title: designHouseSeoTitle,
      description:
        "Morni empowers you to co-create custom pieces with South-Asian artisans, using natural fabrics and transparent supply chains.",
      images: [xBanner],
    },
    icons: {
      apple: APPLE_ICON,
    },
    appleWebApp: {
      capable: true,
      statusBarStyle: "default",
      title: designHouseSeoTitle
    },
  };
}

export default async function Page({
  params,
}: {
  params: Promise<{ slug: string }>;
}) {
  const { slug } = await params;

  const data = await fetchDesignHouseData(slug);
  const dh = data.data.design_house;

  return (
    <>
      <DesignHouseDeails params={{ slug }} initialData={data} />
    </>
  );
}
