import { Plan } from "@prisma/client";
import { hasProFeatures } from "./edition";

export type TitleFields = {
  /** YouTube video title */
  title?: string | null;
  /** On-video song / track title (art-track layouts) */
  songTitle?: string | null;
  artist?: string | null;
};

/** Resolve the title sent to YouTube. Pro may omit video title → `${artist} - ${songTitle}`. */
export function resolveYouTubeTitle(meta: TitleFields, plan: Plan): string {
  const videoTitle = meta.title?.trim();
  if (videoTitle) return videoTitle;

  if (hasProFeatures(plan)) {
    const artist = meta.artist?.trim();
    const song = meta.songTitle?.trim();
    if (artist && song) return `${artist} - ${song}`;
    if (song) return song;
    if (artist) return artist;
  }

  return "";
}

/** Title burned into art-track layout (never the YouTube-only field alone when songTitle set). */
export function resolveBurnedSongTitle(
  meta: TitleFields,
  fallback = "Untitled",
): string {
  return meta.songTitle?.trim() || fallback;
}

export function validateYouTubeTitle(meta: TitleFields, plan: Plan): string | null {
  const resolved = resolveYouTubeTitle(meta, plan);
  if (!resolved) {
    if (hasProFeatures(plan)) {
      return "Enter a video title, or both artist and song title for the YouTube fallback";
    }
    return "Each video must have a video title";
  }
  return null;
}
