export type ElementVariationPickerPartContext = {
  partId?: string;
  partLabel?: string;
  partMeshId?: string;
  partMaterialId?: string;
  variationId?: string;
};

const firstValue = (values: unknown[]): string => {
  for (const value of values) {
    const normalized = String(value ?? '').trim();
    if (normalized) return normalized;
  }
  return '';
};

/** Resolve the picker payload that belongs to the currently displayed variation branch. */
export function resolveElementVariationPickerPartContext(
  pathInput: Array<Record<string, any>> | null | undefined,
  variationId?: string | null,
): ElementVariationPickerPartContext {
  const path = Array.isArray(pathInput) ? pathInput.filter(Boolean) : [];
  const nodes = [...path].reverse();
  const partId = firstValue(nodes.flatMap((node) => [
    node?.product3d?.partId,
    node?.metadata?.asukaProduct3DPartId,
    node?.metadata?.partId,
  ]));
  const partLabel = firstValue(nodes.flatMap((node) => [
    node?.metadata?.asukaProduct3DPartLabel,
    node?.product3d?.partLabel,
    node?.metadata?.partLabel,
  ])) || partId;
  const partMeshId = firstValue(nodes.flatMap((node) => [
    node?.product3d?.meshId,
    node?.product3d?.meshName,
    node?.metadata?.productPartMeshId,
    node?.metadata?.meshId,
  ]));
  const partMaterialId = firstValue(nodes.flatMap((node) => [
    node?.product3d?.materialTarget,
    node?.metadata?.productPartMaterialId,
    node?.metadata?.materialId,
    node?.metadata?.originalMaterialTarget,
    node?.metadata?.materialTarget,
  ]));

  return {
    partId: partId || undefined,
    partLabel: partLabel || undefined,
    partMeshId: partMeshId || undefined,
    partMaterialId: partMaterialId || undefined,
    ...(variationId !== undefined
      ? { variationId: String(variationId ?? '').trim() || undefined }
      : {}),
  };
}
