import type { Metadata } from "next";
import "./globals.css";
import { prisma } from "@/lib/prisma";
import { siteUrl } from "@/lib/utils";

function faviconType(path?: string | null) {
  if (!path) return "image/x-icon";
  if (path.endsWith(".png")) return "image/png";
  if (path.endsWith(".jpg") || path.endsWith(".jpeg")) return "image/jpeg";
  if (path.endsWith(".webp")) return "image/webp";
  if (path.endsWith(".gif")) return "image/gif";
  if (path.endsWith(".svg")) return "image/svg+xml";
  return "image/x-icon";
}

export async function generateMetadata(): Promise<Metadata> {
  let setting: { faviconUrl: string | null; updatedAt: Date } | null = null;
  try {
    setting = await prisma.siteSetting.findUnique({ where: { key: "site" } });
  } catch {
    setting = null;
  }
  const faviconVersion = setting?.updatedAt ? setting.updatedAt.getTime() : Date.now();
  const faviconUrl = `/favicon.ico?v=${faviconVersion}`;

  return {
    metadataBase: new URL(siteUrl()),
    title: {
      default: "Just Chill Nepal",
      template: "%s | Just Chill Nepal"
    },
    description:
      "Bike rides, places, culture, food, and stories from Nepal by Just Chill Nepal.",
    icons: {
      icon: [{ url: faviconUrl, type: faviconType(setting?.faviconUrl), sizes: "any" }],
      shortcut: [{ url: faviconUrl, type: faviconType(setting?.faviconUrl) }],
      apple: [{ url: faviconUrl, type: faviconType(setting?.faviconUrl) }]
    },
    openGraph: {
      title: "Just Chill Nepal",
      description:
        "Discover Nepal through rides, stories, food, culture, and local places.",
      url: siteUrl(),
      siteName: "Just Chill Nepal",
      type: "website"
    }
  };
}

export default function RootLayout({
  children
}: Readonly<{
  children: React.ReactNode;
}>) {
  return (
    <html lang="en" suppressHydrationWarning>
      <body>{children}</body>
    </html>
  );
}
