import type { ContentPlaceholderVars } from "@/lib/contentPlaceholders";
import { LEGACY_DEFAULT_SUBJECT } from "@/lib/contentPlaceholders";
import {
  COURSE_HERO_LEGACY_DEFAULT_NAME,
  COURSE_HERO_NAME_PLACEHOLDER,
  defaultCourseHeroContent,
  normalizeWeeklyTimeValue,
} from "./defaultContent";

function str(value: unknown): string {
  return typeof value === "string" ? value : "";
}

/** Replace legacy library defaults with reusable placeholders. */
export function normalizeCourseHeroContent(
  content: Record<string, unknown>,
  pageVars?: ContentPlaceholderVars
): Record<string, unknown> {
  const next = { ...content };

  const name = str(next.name).trim();
  const pageCourse = str(pageVars?.course_name ?? pageVars?.subject).trim();

  if (!name || name === COURSE_HERO_LEGACY_DEFAULT_NAME) {
    next.name = COURSE_HERO_NAME_PLACEHOLDER;
  } else if (
    name === LEGACY_DEFAULT_SUBJECT &&
    pageCourse &&
    pageCourse !== LEGACY_DEFAULT_SUBJECT
  ) {
    next.name = COURSE_HERO_NAME_PLACEHOLDER;
  }

  next.weeklyTimeK5 = normalizeWeeklyTimeValue(next.weeklyTimeK5);
  next.weeklyTime612 = normalizeWeeklyTimeValue(next.weeklyTime612);

  return next;
}

export function mergeCourseHeroDefaults(content: Record<string, unknown>): Record<string, unknown> {
  return {
    ...defaultCourseHeroContent,
    ...content,
  };
}
