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

import { Client } from '../../../offchain';
import {
  createHistoryItemFirstPart,
  creteHistoryAccessKey,
  HistoryAccess,
  HistoryAccessClaimBody,
  HistoryItemClaimBody,
} from '../shared';

import { HistoryData } from './types';

export const getHistoryByHistoryAccess = async (client: Client, access: HistoryAccess): Promise<HistoryData[]> => {
  const range =
    access.timestamp === undefined
      ? undefined
      : {
          start: null,
          end: [Number.MAX_SAFE_INTEGER - access.timestamp + 1, Number.MAX_SAFE_INTEGER, '~'],
        };

  const claimsResponse = await client.fetchClaims(createHistoryItemFirstPart(access.historyId), null, range);

  return claimsResponse.map((claim) => {
    const keySecondPart = (claim.content.key as ClaimKey).second_part as [number, number];

    return {
      ...(claim.content.body as HistoryItemClaimBody),
      timestamp: Number.MAX_SAFE_INTEGER - keySecondPart[0],
      order: keySecondPart[1],
      access,
    };
  });
};

export const getHistoryAccess = async (client: Client, uniqueId: string): Promise<HistoryAccess | undefined> => {
  const key = creteHistoryAccessKey(uniqueId);

  const access = (await client.fetchClaims(key.first_part, key.second_part))[0]?.content.body as
    | HistoryAccessClaimBody
    | undefined;

  return access;
};
