import type { Metadata } from "next";
import type { SeoContent } from "@/lib/content/types";

const siteName = "Funktechnik Schubert";
const defaultTitle = "Funktechnik Schubert | Funkgeräte-Service & Messtechnik";
const siteUrl = process.env.NEXT_PUBLIC_SITE_URL ?? "http://127.0.0.1:3010";
const keywords = [
  "Funktechnik Schubert",
  "Funkgeräte Reparatur",
  "CB Funk Service",
  "Amateurfunk Service",
  "Funkgeräte Abgleich",
  "Funkgeräte Diagnose",
  "Messtechnik",
  "Funktechnik Service",
  "Kommunikationstechnik",
  "Service Manual",
  "Schaltplan",
  "Funkwerkstatt",
  "Reparaturannahme",
];

export function createMetadata(title: string, description: string, path = "/"): Metadata {
  const url = new URL(path, siteUrl).toString();
  const fullTitle = title === siteName ? title : `${title} | ${siteName}`;

  return {
    metadataBase: new URL(siteUrl),
    title: title === siteName ? { default: defaultTitle, template: `%s | ${siteName}` } : fullTitle,
    applicationName: siteName,
    description,
    keywords,
    icons: {
      icon: [
        { url: "/favicon.ico", sizes: "any" },
        { url: "/favicon-16x16.png", sizes: "16x16", type: "image/png" },
        { url: "/favicon-32x32.png", sizes: "32x32", type: "image/png" },
      ],
      apple: [{ url: "/apple-touch-icon.png", sizes: "180x180", type: "image/png" }],
    },
    alternates: {
      canonical: url,
    },
    openGraph: {
      type: "website",
      locale: "de_DE",
      url,
      siteName,
      title: fullTitle,
      description,
      images: [
        {
          url: "/funktechnik_schubert_logo.jpg",
          width: 1672,
          height: 941,
          alt: siteName,
        },
      ],
    },
  };
}

export function createContentMetadata(seo: SeoContent, fallbackSeo?: SeoContent): Metadata {
  const resolvedSeo = {
    ...fallbackSeo,
    ...Object.fromEntries(Object.entries(seo).filter(([, value]) => value.trim() !== "")),
  } as SeoContent;
  const path = resolvedSeo.canonicalUrl || "/";
  const url = new URL(path, siteUrl).toString();
  const title = resolvedSeo.metaTitle || siteName;
  const description = resolvedSeo.metaDescription || defaultTitle;

  return {
    ...createMetadata(title, description, path),
    keywords: resolvedSeo.keywords ? resolvedSeo.keywords.split(",").map((keyword) => keyword.trim()).filter(Boolean) : keywords,
    openGraph: {
      type: "website",
      locale: "de_DE",
      url,
      siteName,
      title: resolvedSeo.openGraphTitle || title,
      description: resolvedSeo.openGraphDescription || description,
      images: [
        {
          url: resolvedSeo.socialImage || "/funktechnik_schubert_logo.jpg",
          width: 1200,
          height: 630,
          alt: resolvedSeo.openGraphTitle || title,
        },
      ],
    },
  };
}

export { defaultTitle, siteName, siteUrl };
