import { uint8ArrayToHexString, uint8ArrayFromHexString } from '@turnkey/encoding';

import { getPublicKey } from '@turnkey/crypto';
import axios from 'axios';
import { WalletType as TurnkeyWalletType } from '@turnkey/wallet-stamper';

export const getPublicKeyFromPrivateKeyHex = (privateKey: string): string => {
  return uint8ArrayToHexString(getPublicKey(uint8ArrayFromHexString(privateKey), true));
};

/**
 * Get an item from localStorage. If it has expired, remove
 * the item from localStorage and return null.
 * @param {string} key
 */
export const getItemWithExpiry = (key: string) => {
  const itemStr = localStorage.getItem(key);

  if (!itemStr) {
    return null;
  }

  const item = JSON.parse(itemStr);

  // eslint-disable-next-line no-prototype-builtins
  if (!item.hasOwnProperty('expiry') || !item.hasOwnProperty('value')) {
    window.localStorage.removeItem(key);
    return null;
  }

  const now = new Date();
  if (now.getTime() > item.expiry) {
    window.localStorage.removeItem(key);
    return null;
  }
  return item.value;
};

/**
 * Set an item in localStorage with an expiration time
 * @param {string} key
 * @param {string} value
 * @param {number} ttl expiration time in milliseconds
 */
export const setItemWithExpiry = (key: string, value: string, ttl: number) => {
  const now = new Date();
  const item = {
    value: value,
    expiry: now.getTime() + ttl,
  };
  localStorage.setItem(key, JSON.stringify(item));
};

export const handleTurnkeyApiKeys = async (
  organizationId: string,
  walletType: TurnkeyWalletType | 'delegation',
  errorHandler: (error: Error) => void,
): Promise<string> => {
  try {
    const { data } = await axios.post(`/api/create-wallet-api-key`, {
      walletType,
      organizationId,
    });

    const { publicKey } = data?.data;
    if (!publicKey) throw new Error('Missing public key');

    return publicKey;
  } catch (error) {
    console.error('Error handling API key:', error);
    errorHandler(error as Error);

    return '';
  }
};
