import type { ThreadPlay } from "./types";

export function speakersOf(play: Pick<ThreadPlay, "lead_account_id" | "cast_account_ids">): string[] {
  const set = new Set<string>([play.lead_account_id, ...play.cast_account_ids]);
  return [...set].filter(Boolean);
}

export function isUnderPostScheme(
  play: Pick<ThreadPlay, "target_own_post_id" | "target_external">,
): boolean {
  return Boolean(play.target_own_post_id) || Boolean(play.target_external?.url);
}

/**
 * 整串（含主貼）校驗。
 * 回傳 i18n key（play.err.*），通過則 null。
 */
export function validatePlaySteps(
  play: Pick<
    ThreadPlay,
    "lead_account_id" | "cast_account_ids" | "steps" | "target_own_post_id" | "target_external"
  >,
): string | null {
  if (isUnderPostScheme(play)) {
    return validateUnderPostScheme(play);
  }
  if (!play.lead_account_id) return "play.err.needLead";
  if (!play.steps.length) return "play.err.needRoot";
  const root = play.steps.find((s) => s.kind === "root") || play.steps[0];
  if (!root || root.kind !== "root") return "play.err.firstMustRoot";
  if (root.account_id !== play.lead_account_id) return "play.err.rootMustLead";
  if (!root.text.trim()) return "play.err.rootEmpty";

  const speakers = new Set(speakersOf(play));
  for (const step of play.steps) {
    if (step.kind === "reply") {
      if (!speakers.has(step.account_id)) return "play.err.replyAccount";
      if (!step.text.trim()) return "play.err.replyEmpty";
    }
  }
  return null;
}

/**
 * 貼文下互回方案校驗。回傳 i18n key 或 null。
 */
export function validateUnderPostScheme(
  play: Pick<
    ThreadPlay,
    "lead_account_id" | "cast_account_ids" | "steps" | "target_own_post_id" | "target_external"
  >,
): string | null {
  if (!play.target_own_post_id && !play.target_external?.url) {
    return "play.err.needTarget";
  }
  if (!play.steps.length) return "play.err.needReplies";
  const speakers = new Set(speakersOf(play));
  if (speakers.size === 0) return "play.err.needReplyAccounts";
  for (const step of play.steps) {
    if (!step.account_id || !speakers.has(step.account_id)) {
      return "play.err.stepAccount";
    }
    if (!step.text.trim()) return "play.err.stepEmpty";
  }
  return null;
}
