/**
 * Shared encode/decode for the custom_fields JSON blob carried by customers
 * AND warehouse suppliers (one column, PHP-compatible format:
 * `{ "fields": [{name, value, showLabel}], "field_order": [...] }`).
 * Lifted from routes/admin/customers.ts when suppliers gained the same
 * "Vlastní pole" model (2026-06).
 */

/** Encode custom_fields + field_order into a single JSON blob (matching PHP format). */
export function encodeCustomFields(
  fields: unknown,
  fieldOrder: unknown,
): string | null {
  const f = Array.isArray(fields) ? fields : [];
  const o = Array.isArray(fieldOrder) ? fieldOrder : [];
  if (f.length === 0 && o.length === 0) return null;
  return JSON.stringify({ fields: f, field_order: o });
}

/** Decode the custom_fields JSON blob into separate fields + field_order for the frontend. */
export function decodeCustomFields(raw: string | null): {
  custom_fields: unknown[];
  field_order: string[];
} {
  if (!raw) return { custom_fields: [], field_order: [] };
  try {
    const parsed = JSON.parse(raw);
    // PHP format: { fields: [...], field_order: [...] }
    if (
      parsed &&
      typeof parsed === "object" &&
      !Array.isArray(parsed) &&
      "fields" in parsed
    ) {
      return {
        custom_fields: parsed.fields || [],
        field_order: parsed.field_order || [],
      };
    }
    // Legacy TS format: raw array
    if (Array.isArray(parsed)) {
      return { custom_fields: parsed, field_order: [] };
    }
    return { custom_fields: [], field_order: [] };
  } catch {
    return { custom_fields: [], field_order: [] };
  }
}
