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

import { getContext } from '../../../../onchain';
import { HistoryItem } from '../../shared';
import { createHistoryClaim } from '../claims';
import { getMetadata, setSetMetadata } from '../metadata/metadata';
import { updateMetadata } from '../metadata/updateMetadata';

import { forceHistoryId } from './forceHistoryId';

export const constructHistoryItem = ({
  historyItem,
  historyId: providedHistoryId,
}: {
  historyId?: string;
  historyItem: HistoryItem;
}) => {
  const metadata = getMetadata();

  const uniqueId = getContext().call.txid.slice(0, 16);
  const order = metadata?.historyOrder ?? 0;

  const historyId = providedHistoryId ?? forceHistoryId();

  if (historyId !== providedHistoryId) {
    if (metadata?.historyLink) {
      const externalLink = metadata.historyLink;

      historyItem.links = [...(historyItem.links ?? []), externalLink];

      setSetMetadata({
        ...metadata,
        historyLink: null,
      });
    }
  }

  if (!historyId) {
    return [];
  }

  const historyClaim = createHistoryClaim({
    historyId,
    historyItem: { ...historyItem, links: historyItem.links ?? null },
    uniqueId,
    order,
  });

  updateMetadata({ historyOrder: order + 1 });

  return [constructStore(historyClaim)];
};
