import { isObject, isString } from './utils';

export type Metadata = Record<
  string,
  string | boolean | number | null | undefined
>;

export const fixCaption = (caption: unknown): string | undefined => {
  if (caption === undefined) {
    return undefined;
  }
  if (isString(caption)) {
    return caption;
  }
  return undefined;
};

export const fixStyleSummary = (styleSummary: unknown): string | undefined => {
  if (styleSummary === undefined) {
    return undefined;
  }
  if (isString(styleSummary)) {
    return styleSummary;
  }
  return undefined;
};

export const fixMetadata = (metadata: unknown): Metadata | undefined => {
  if (metadata === undefined) {
    return undefined;
  }
  if (!isObject(metadata)) {
    return undefined;
  }
  // Remove fields with invalid value types to keep referentially stable
  for (const [key, value] of Object.entries(metadata)) {
    const valueType = typeof value;
    if (
      valueType !== 'string' &&
      valueType !== 'boolean' &&
      valueType !== 'number' &&
      value !== null &&
      value !== undefined
    ) {
      delete metadata[key];
    }
  }
  return metadata as Metadata;
};
