import { getSettings } from "../getSettings";
import { getMetaSlug } from "./getMetaSlug";

const normalizeSlug = (slug) => {
  if (Array.isArray(slug)) slug = slug.join("/");

  return slug;
};

export const generateDynamicMeta = async (slug) => {
  try {
    slug = normalizeSlug(slug);
    const seoRes = await getMetaSlug(slug);
    if (!seoRes?.ok) {
      return {
        title: "Selvakumar Jewellary",
        description: "Discover exquisite jewelry at Selvakumar Jewellary",
      };
    }

    const { product, category, collection, meta } = seoRes;

    const [rows] = await getSettings();
    const settings = rows.reduce((acc, curr) => {
      acc[curr.settings_name] = curr.settings_value;
      return acc;
    }, {});

    // 🔹 Fallbacks
    const fallbackTitle =
      product?.name ||
      category?.name ||
      collection?.name ||
      settings?.name ||
      "Selvakumar Jewellary";

    const fallbackDesc =
      product?.description ||
      category?.description ||
      collection?.description ||
      `Explore ${fallbackTitle}`;

    const fallbackImage =
      product?.product_image?.split(",")[0]?.replace("/api", "") ||
      category?.category_image?.replace("/api", "") ||
      collection?.image?.replace("/api", "") ||
      settings?.logo?.replace("/api", "") ||
      "";

    const metadata = {
      title: `${fallbackTitle} | ${settings?.name || "Selvakumar Jewellary"}`,
      description: fallbackDesc,
      openGraph: {
        title: `${fallbackTitle} | ${settings?.name || "Selvakumar Jewellary"}`,
        description: fallbackDesc,
        images: fallbackImage ? [{ url: fallbackImage }] : [],
      },
      twitter: {
        title: `${fallbackTitle} | ${settings?.name || "Selvakumar Jewellary"}`,
        description: fallbackDesc,
      },
    };

    // 🔹 Apply meta overrides
    if (meta?.metas?.length) {
      meta.metas.forEach((m) => {
        const value = m.is_content ? m.content : m.image;
        if (!value) return;

        if (m.attribute_scope === "general") {
          if (m.attribute_key === "title") {
            metadata.title = `${value} | ${settings?.name || "Selvakumar Jewellary"}`;
          }
          if (m.attribute_key === "description") {
            metadata.description = value;
          }
        }

        if (m.attribute_scope === "og") {
          if (m.attribute_key === "image") {
            metadata.openGraph.images = [{ url: value?.replace("/api", "") }];
          } else {
            metadata.openGraph[m.attribute_key] = value?.replace("/api", "");
          }
        }

        if (m.attribute_scope === "twitter") {
          if (m.attribute_key === "image") {
            metadata.twitter.image = value?.replace("/api", "");
          } else {
            metadata.twitter[m.attribute_key] = value?.replace("/api", "");
          }
        }
      });

      // ensure fallbacks
      metadata.openGraph.title ??= metadata.title;
      metadata.openGraph.description ??= metadata.description;
      metadata.twitter.title ??= metadata.title;
      metadata.twitter.description ??= metadata.description;

      if (!metadata.openGraph.images?.length && fallbackImage) {
        metadata.openGraph.images = [{ url: fallbackImage }];
      }
      if (!metadata.twitter.image && fallbackImage) {
        metadata.twitter.image = fallbackImage;
      }
    }

    // 🔹 Icons + base
    metadata.icons = {
      icon: [
        {
          url: settings?.icon?.replace("/api", "") || "/images/logo-dark.png",
          type: settings?.icon?.endsWith(".webp") ? "image/webp" : "image/png",
        },
      ],
    };

    metadata.metadataBase = new URL(
      settings?.website || "https://swarnalayajewels.com"
    );

    return metadata;
  } catch (error) {
    console.error("❌ Error generating metadata:", error);
    return {
      title: "Selvakumar Jewellary",
      description: "Discover exquisite jewelry at Selvakumar Jewellary",
    };
  }
};
