import { formatDateTime as formatPlatformDateTime } from "../../utils/datetime";

export function adminErrorMessage(error: unknown): string {
  if (!(error instanceof Error)) return "i18n:govoplan-core.the_administrative_operation_failed.0791d379";
  const message = error.message;
  const jsonStart = message.indexOf("{");
  if (jsonStart >= 0) {
    try {
      const parsed = JSON.parse(message.slice(jsonStart)) as {detail?: unknown;};
      if (typeof parsed.detail === "string") return parsed.detail;
      if (Array.isArray(parsed.detail)) {
        return parsed.detail.map((item) => typeof item === "object" && item && "msg" in item ? String((item as {msg: unknown;}).msg) : String(item)).join("; ");
      }
      if (typeof parsed.detail === "object" && parsed.detail) {
        const detail = parsed.detail as {message?: unknown;plan?: {blockers?: unknown;warnings?: unknown;};};
        const blockers = detail.plan?.blockers;
        const warnings = detail.plan?.warnings;
        const parts = [];
        if (typeof detail.message === "string") parts.push(detail.message);
        if (Array.isArray(blockers) && blockers.length > 0) {
          parts.push(`Blockers: ${blockers.map(String).join(", ")}`);
        }
        if (Array.isArray(warnings) && warnings.length > 0) {
          parts.push(`Warnings: ${warnings.map(String).join(", ")}`);
        }
        if (parts.length > 0) return parts.join(" ");
      }
    } catch {


      // Fall through to the original message.
    }}return message;
}

export function formatAdminDateTime(value?: string | null): string {
  return formatPlatformDateTime(value, { fallback: "i18n:govoplan-core.never.80c3052d" });
}

export function joinLabels(values: Array<{name: string;}>): string {
  return values.length ? values.map((value) => value.name).join(", ") : "—";
}