import { flattenContentfulContent } from './transformContentfulContent';
import type { ContentAuthor } from '@nacelle/types';
import type { SourceName } from './destructureNacelleEntryId';

interface UnformattedAuthor {
  [key: string]: string | null;
}

export function transformAuthor(
  authorInput: UnformattedAuthor | null,
  cms: SourceName
): ContentAuthor | null {
  if (
    !authorInput ||
    typeof authorInput !== 'object' ||
    Array.isArray(authorInput)
  ) {
    return null;
  }

  const newAuthor: ContentAuthor = {
    bio: null,
    email: null,
    firstName: null,
    lastName: null
  };

  const author =
    cms === 'CONTENTFUL' ? flattenContentfulContent(authorInput) : authorInput;

  for (const [key, value] of Object.entries(author)) {
    const property = key as keyof ContentAuthor;

    if (
      typeof value === 'string' &&
      value.length &&
      typeof newAuthor[property] !== 'undefined' // Check that `property` is a valid property of `ContentAuthor`
    ) {
      newAuthor[key as keyof ContentAuthor] = value;
    }
  }

  return newAuthor;
}
