import { Context, getMethodArguments } from '@coinweb/contract-kit';

import { setIsNewHistoryAccessId } from './isNewHistoryAccessId';
import { setSetMetadata } from './metadata';
import { validateMetadata } from './validateMetadata';

export const setMetadata = (context: Context) => {
  const args = getMethodArguments(context);

  const metadataArg = args.findLast(validateMetadata);

  if (metadataArg) {
    const historyOrder =
      ('_historyOrder' in metadataArg._metadata ? metadataArg._metadata._historyOrder : null) ?? null;
    const historyLink = ('_historyLink' in metadataArg._metadata ? metadataArg._metadata._historyLink : null) ?? null;
    const currentAccessId =
      ('_currentAccessId' in metadataArg._metadata ? metadataArg._metadata._currentAccessId : null) ?? null;

    const newAccessId = ('_newAccessId' in metadataArg._metadata ? metadataArg._metadata._newAccessId : null) ?? null;

    const trackingId = '_trackingId' in metadataArg._metadata ? metadataArg._metadata._trackingId : null;

    if (trackingId) {
      setSetMetadata({
        trackingId,
        historyOrder,
        historyLink,
        accessId: currentAccessId,
      });
    } else {
      setSetMetadata({
        trackingId: null,
        historyOrder: null,
        historyLink,
        accessId: newAccessId,
      });
    }

    if (newAccessId) {
      setIsNewHistoryAccessId(true);
    }
  }
};
