import { Metadata } from "next";
import { cookies } from "next/headers";

import { getMerchantPageDataServer } from "@/services/coupon.service.server";
import config from "@/utils/config";
import { toTitleCase } from "@/utils/helper";

type Props = {
  params: Promise<{ store: string }>;
  children: React.ReactNode;
};

function escapeRegExp(value: string): string {
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

function withUkQualifier(text: string, brand: string): string {
  if (/\bUK\b/i.test(text)) {
    return text;
  }

  const brandRegex = new RegExp(`\\b${escapeRegExp(brand)}\\b`, "i");
  if (brandRegex.test(text)) {
    return text.replace(brandRegex, `${brand} UK`);
  }

  return `${brand} UK ${text}`.trim();
}

export async function generateMetadata({ params }: Props): Promise<Metadata> {
  const { store = "amazon.com" } = await params;
  const isUkStore = /\.co\.uk$/i.test(store);
  const brandName = toTitleCase(
    store.replace(/^www\./i, "").replace(/\.(co\.uk|com)$/i, ""),
  );

  const res = await getMerchantPageDataServer(store);
  const data = res?.data;

  const cookieStore = await cookies();
  const userType = cookieStore.get("user_type");

  const rawTitle = toTitleCase(
    data?.page_title || `${store} Coupons & Deals | Rebates.com`,
  );
  const rawDescription =
    data?.meta_description || `Find the best coupons and deals for ${store}`;

  const title = isUkStore ? withUkQualifier(rawTitle, brandName) : rawTitle;
  const description = isUkStore
    ? withUkQualifier(rawDescription, brandName)
    : rawDescription;

  return {
    title,
    description,
    alternates: {
      canonical: `/coupons/${store}`,
    },
    icons: {
      icon:
        userType?.value === "PLUS"
          ? config.APP_CONFIG.PLUS_FAVICON
          : config.APP_CONFIG.FAVICON,
    },
    openGraph: {
      title,
      description,
      type: "website",
    },
  };
}

export default function CouponStoreLayout({ children }: Props) {
  return children;
}
