import dayjs from "dayjs";
import { arrayToDateString } from "@/app/utils/formatUtil";

/** Normalize API targetDate (string or date array) to YYYY-MM-DD for search / URL. */
export function normalizeTargetDateInput(value: unknown): string | null {
  if (value == null || value === "") {
    return null;
  }
  try {
    if (Array.isArray(value)) {
      const s = arrayToDateString(value, "input");
      return dayjs(s).isValid() ? dayjs(s).format("YYYY-MM-DD") : null;
    }
    const d = dayjs(String(value));
    return d.isValid() ? d.format("YYYY-MM-DD") : null;
  } catch {
    return null;
  }
}

export function resolveWorkbenchRecordTargetDate(initial?: string | null): string {
  return normalizeTargetDateInput(initial) ?? dayjs().format("YYYY-MM-DD");
}
