// Baut aus dem JSON-Body der Team-API eine FormData, wie sie
// createTodoAction / updateTodoAction erwarten — damit dieselbe Logik
// (inkl. Berechtigungen) wiederverwendet wird. Deckt jetzt auch Labels,
// Projekt, Unteraufgaben, weitere Zuständige/Beobachter und die
// erweiterte Wiederholung ab.
type Body = Record<string, unknown> | null;

const asStr = (v: unknown) => (typeof v === "string" ? v : "");
const strArr = (v: unknown) => (Array.isArray(v) ? v.filter((x): x is string => typeof x === "string") : []);

export function todoBodyToFormData(body: Body): FormData {
  const fd = new FormData();
  fd.set("title", asStr(body?.title));
  fd.set("description", asStr(body?.description));
  if (body?.dueDate) fd.set("dueDate", String(body.dueDate));
  fd.set("priority", typeof body?.priority === "string" ? (body.priority as string) : "normal");
  if (asStr(body?.assignedToId)) fd.set("assignedToId", asStr(body?.assignedToId));
  if (asStr(body?.orderId)) fd.set("orderId", asStr(body?.orderId));

  if (Array.isArray(body?.labels)) fd.set("labels", strArr(body?.labels).join(","));
  else if (typeof body?.labels === "string") fd.set("labels", body.labels);
  if (typeof body?.project === "string") fd.set("project", body.project);
  if (Array.isArray(body?.subtasks)) fd.set("subtasks", strArr(body?.subtasks).join("\n"));

  if (Array.isArray(body?.additionalAssigneeIds)) {
    fd.set("peopleEdited", "1");
    for (const id of strArr(body?.additionalAssigneeIds)) fd.append("additionalAssigneeIds", id);
  }
  if (Array.isArray(body?.watcherIds)) {
    fd.set("peopleEdited", "1");
    for (const id of strArr(body?.watcherIds)) fd.append("watcherIds", id);
  }

  fd.set("recurrence", typeof body?.recurrence === "string" ? (body.recurrence as string) : "none");
  if (body?.recurrenceInterval != null) fd.set("recurrenceInterval", String(body.recurrenceInterval));
  if (Array.isArray(body?.recurrenceWeekdays)) {
    for (const d of body.recurrenceWeekdays) fd.append("recurrenceWeekdays", String(d));
  }
  if (body?.recurrenceEndDate) fd.set("recurrenceEndDate", String(body.recurrenceEndDate));

  return fd;
}
