import { DEFAULT_LANGUAGE, type AppLanguage } from "@/lib/i18n/registry";
import { formatLocalizedSeoTitle } from "@/lib/i18n/seo";
import { translateCommon } from "@/lib/i18n/translate";

type CourseSeoInput = {
  _id?: string;
  cuorse_name?: string;
  category?: string;
  teacher_name?: string;
  caption?: string;
  price?: string | number;
  offer?: string | number;
  is_free?: boolean;
  finalPrice?: number;
};

export function formatCoursePriceLabel(
  course: CourseSeoInput,
  lang: AppLanguage = DEFAULT_LANGUAGE
): string {
  if (course.is_free) {
    return translateCommon(lang, "academy.course.free");
  }

  const basePrice = Number(course.finalPrice ?? course.price) || 0;
  const locale = lang === "fa" ? "fa-IR" : "en-US";
  return translateCommon(lang, "courseSeo.priceToman", {
    price: basePrice.toLocaleString(locale),
  });
}

export function buildCourseDetailSeo(
  course: CourseSeoInput,
  id: string,
  lang: AppLanguage = DEFAULT_LANGUAGE
) {
  const courseName =
    course.cuorse_name ||
    translateCommon(lang, "courseSeo.defaultPackage");
  const category =
    course.category || translateCommon(lang, "courseSeo.defaultCategory");
  const teacher =
    course.teacher_name || translateCommon(lang, "courseSeo.defaultTeacher");
  const rawCaption = (course.caption || "").replace(/<[^>]*>?/gm, "").trim();
  const priceLabel = formatCoursePriceLabel(course, lang);
  const titleCore = `${courseName} – ${category} – ${teacher}`;

  return {
    title: formatLocalizedSeoTitle(titleCore, lang),
    description: [rawCaption || courseName, priceLabel].filter(Boolean).join(" - "),
    path: `/academy/${id}/${encodeURIComponent(courseName)}`,
  };
}
