import { getChunkedCreationList } from '@/services/creations';
import { getCreatorList } from '@/services/creators';

import {
  HOMEPAGE_MAP_CONTENT_TYPES,
  HOMEPAGE_MAP_CREATOR_META_IDS,
  HOMEPAGE_MAP_EXCLUDED_CREATION_IDS,
  type HomepageMapCreatorOption,
} from '@/components/home/blocks/homepageMapShowcaseConfig';
import { toNonEmptyString } from '@/utils/stringNormalization';

import type { CreationListItem } from '@/types/Creation';
import type { CreatorListData } from '@/types/Creator';

export interface HomepageMapData {
  creations: CreationListItem[];
  creatorOptions: HomepageMapCreatorOption[];
}

const toCreationArray = (response: unknown): CreationListItem[] => {
  if (Array.isArray(response)) return response as CreationListItem[];

  if (
    response &&
    typeof response === 'object' &&
    'list' in response &&
    Array.isArray((response as { list?: unknown }).list)
  ) {
    return (response as { list: CreationListItem[] }).list;
  }

  return [];
};

// The map only shows pins (coordinates, title, main image, creator, year, place), so
// videos and creator portraits are dropped from the payload.
const toMapCreation = (creation: CreationListItem): CreationListItem => ({
  ...creation,
  hivatkozasLista: null,
  alkoto: creation.alkoto.map(({ alkotoAzonosito, megjelenitendoNev, szakma }) => ({
    alkotoAzonosito,
    megjelenitendoNev,
    szakma,
  })),
});

const toCreatorOption = (creator: CreatorListData): HomepageMapCreatorOption | null => {
  const id = toNonEmptyString(creator.alkotoAzonosito);
  const name = toNonEmptyString(creator.nev);
  if (!id || !name) return null;

  return {
    alkotoAzonosito: id,
    nev: name,
    szakma: toNonEmptyString(creator.szakma),
    // Avatars only need the image id.
    profilkep: creator.profilkep?.id ? { id: creator.profilkep.id } : null,
    elhalalozasIdeje: creator.elhalalozasIdeje,
  };
};

const loadCreatorOptions = async (): Promise<HomepageMapCreatorOption[]> => {
  const creators = await getCreatorList({
    body: {
      metaIdList: [...HOMEPAGE_MAP_CREATOR_META_IDS],
      withCoord: true,
    },
  });

  const byId = new Map<string, HomepageMapCreatorOption>();
  for (const creator of creators) {
    const option = toCreatorOption(creator);
    if (!option) continue;
    if (byId.has(option.alkotoAzonosito)) continue;
    byId.set(option.alkotoAzonosito, option);
  }

  return Array.from(byId.values()).sort((left, right) => left.nev.localeCompare(right.nev, 'hu'));
};

const loadCreations = async (): Promise<CreationListItem[]> => {
  const response = await getChunkedCreationList({
    contentType: [...HOMEPAGE_MAP_CONTENT_TYPES],
    withCoord: true,
    imageNeeded: true,
  });

  return toCreationArray(response)
    .filter((creation) => !HOMEPAGE_MAP_EXCLUDED_CREATION_IDS.has(creation.alkotasAzonosito))
    .map(toMapCreation);
};

/** Data of the homepage map block, loaded by the browser once the block nears the viewport. */
export async function getHomepageMapData(): Promise<HomepageMapData> {
  const [creations, creatorOptions] = await Promise.all([loadCreations(), loadCreatorOptions()]);
  return { creations, creatorOptions };
}
