const APPLICATION_ANSWER_START = "<<<APPLICATION_ANSWER_DRAFT>>>";
const APPLICATION_ANSWER_END = "<<<END_APPLICATION_ANSWER_DRAFT>>>";

export function extractApplicationAnswerDraft(notes?: string | null) {
  const value = (notes ?? "").trim();
  if (!value) return "";

  const startIndex = value.indexOf(APPLICATION_ANSWER_START);
  const endIndex = value.indexOf(APPLICATION_ANSWER_END);
  if (startIndex >= 0 && endIndex > startIndex) {
    return value.slice(startIndex + APPLICATION_ANSWER_START.length, endIndex).trim();
  }

  const legacyMatch = value.match(/Application answer draft:\s*\n([\s\S]*)$/i);
  return legacyMatch?.[1]?.trim() ?? "";
}

export function removeApplicationAnswerDraft(notes?: string | null) {
  const value = notes ?? "";
  const markerPattern = new RegExp(`${APPLICATION_ANSWER_START}[\\s\\S]*?${APPLICATION_ANSWER_END}`, "g");
  const withoutMarkers = value.replace(markerPattern, "").trim();
  const legacyIndex = withoutMarkers.search(/Application answer draft:\s*\n/i);
  return (legacyIndex >= 0 ? withoutMarkers.slice(0, legacyIndex) : withoutMarkers).trim();
}

export function upsertApplicationAnswerDraft(notes: string | null | undefined, draft: string) {
  const humanNotes = removeApplicationAnswerDraft(notes);
  const answer = draft.trim();
  const block = answer ? `${APPLICATION_ANSWER_START}\n${answer}\n${APPLICATION_ANSWER_END}` : "";
  return [humanNotes, block].filter(Boolean).join("\n\n");
}
