import { ClaimKey } from '@coinweb/contract-kit';
import { Client } from 'lib/offchain';

import { SetClaimBody, WordClaimBody } from './shared';
import { createWordFirstPart, createSetKey, createWordKey, createByLetterFirstPart } from './shared/keys';

export const getWord = async (client: Client, id: string) => {
  const key = createWordKey(id);

  const claimResponse = (await client.fetchClaims(key.first_part, key.second_part))[0];

  const data = claimResponse.content.body as WordClaimBody;

  return data.word;
};

export const getWords = async (client: Client): Promise<string[]> => {
  const claimsResponse = await client.fetchClaims(createWordFirstPart(), null);

  return claimsResponse.map(({ content }) => (content.body as WordClaimBody).word);
};

export const getWordsByLetter = async (client: Client, letter: string): Promise<string[]> => {
  const indexResponse = await client.fetchClaims(createByLetterFirstPart(letter), null);

  const ids = indexResponse.map(({ content }) => ((content.key as ClaimKey).second_part as [string])[0]);

  const words = await Promise.all(ids.map((id) => getWord(client, id)));

  return words;
};

export const getSet = async (client: Client, letter: string): Promise<string> => {
  const key = createSetKey(letter);

  const claimResponse = (await client.fetchClaims(key.first_part, key.second_part))[0];

  const data = claimResponse.content.body as SetClaimBody;

  return data.set;
};
