import { EventInput } from "./types";

// Escapes single quotes for a YAML single-quoted scalar (doubling is the
// YAML-spec escape for ' inside a '...' string).
function yamlSingleQuoted(value: string): string {
  return `'${value.replace(/'/g, "''")}'`;
}

// Matches the frontmatter schema www-new's lib/events.ts already reads
// (RawMetadata): name, short, startDate, endDate?, online, location,
// registerLink?, poster?. `posterRelativePath` is the path the image was
// committed at (see posterRelativePath below), omitted entirely if there's
// no poster.
export function renderEventMarkdown(event: EventInput, posterRelativePath?: string): string {
  const lines = [
    "---",
    `name: ${yamlSingleQuoted(event.name)}`,
    `short: ${yamlSingleQuoted(event.short)}`,
    `startDate: ${yamlSingleQuoted(event.startDate)}`,
  ];

  if (event.endDate) {
    lines.push(`endDate: ${yamlSingleQuoted(event.endDate)}`);
  }

  lines.push(`online: ${event.online}`);
  lines.push(`location: ${yamlSingleQuoted(event.location)}`);

  if (posterRelativePath) {
    lines.push(`poster: ${yamlSingleQuoted(posterRelativePath)}`);
  }

  if (event.registerLink) {
    lines.push(`registerLink: ${yamlSingleQuoted(event.registerLink)}`);
  }

  lines.push("---", "", event.descriptionMarkdown.trimEnd(), "");

  return lines.join("\n");
}

// content/events/{year}/{term}/{slug}.md, matching www-new's EVENTS_PATH
// layout in lib/events.ts.
export function eventRelativePath(event: EventInput): string {
  return `content/events/${event.year}/${event.term}/${event.slug}.md`;
}

// images/events/{year}/{term}/{filename}, matching the legacy Eventer app's
// copyPoster convention so www-new's <Image src={poster}> path resolves
// the same way it always has.
export function posterRelativePath(event: EventInput, filename: string): string {
  return `images/events/${event.year}/${event.term}/${filename}`;
}
