import axios from 'axios'

import {
	IActivDirectSearchAssetParams,
	ILitAction,
	CONTRACT_INTERFACES,
} from '../../..'

const testPricing = async (
	params: IActivDirectSearchAssetParams,
): Promise<CONTRACT_INTERFACES.IPrice> => {
	const headers = {
		'User-Agent': 'PostmanRuntime/7.29.2',
		Accept: 'application/json, text/plain, */*',
		'Accept-Encoding': 'gzip, deflate, br',
		'Accept-Language': 'en-US,en;q=0.9,pt-BR;q=0.8,pt;q=0.7,en-XA;q=0.6',
		Connection: 'keep-alive',
	}

	// Precheck symbol schema
	if (typeof params.symbol !== 'string' || params.symbol === undefined) {
		throw new Error('UnknownSymbol')
	}
	if (params.symbol.length <= 3) {
		throw new Error('UnknownSymbol')
	}
	const symbols = params.symbol.split('=')
	if (!Array.isArray(symbols) || symbols.length !== 2) {
		throw new Error(
			'UnknownSymbol: CryptoCompare requires split symbol with "=" like in: "BTC=USD"',
		)
	}

	const requestRecipe = {
		url:
			'https://min-api.cryptocompare.com/data/price?fsym=' +
			symbols[0] +
			'&tsyms=' +
			symbols[1] +
			'&api_key=' +
			(params.key || 'none'),
		method: 'GET',
		headers,
	}

	const data = await axios
		.get(requestRecipe.url, {
			headers,
			timeout: 0,
		})
		.then((res) => {
			// console.log('data', res.data)
			return res.data
		})

	const globalPrice = data['USD'] || 0
	const timestamp = Date.now()
	const priceObj: CONTRACT_INTERFACES.IPrice = {
		globalPrice,
		provider: 'CryptoCompare',
		symbol: params.symbol,
		timestamp,
	}

	return priceObj
}

/*
 Final action:
 Network: Lit Chronicle
 Onwer Account Wallet: FIRED! => Mint&Grant&Burned! => SECURED!
 PKP id: 38068515139662453389354422133966956597767235759827037216463572151792326299883
 PKP public key: 0x0404c30734f39c3827ec3251f7b1d456c73969a4b9154c496860af44cc2f6b46008c863450ae27820539682a7df05e14e959460cb09e6a48ea3135006ee6f0baac
 PKP ETH: 0xf7c5c7a2Beb1669638F238Ef40cE5C8d41d67D3B
 Action ipfsId: QmUSXgFrUPVqVm1UjgbguEzQanSckGdsWYYQLxTYqay46Y
 granted?: true
 */
export const GET_PRICE_CRYPTOCOMPARE_V2: ILitAction = {
	ipfsId: 'QmUSXgFrUPVqVm1UjgbguEzQanSckGdsWYYQLxTYqay46Y',
	publicKey:
		'0x0404c30734f39c3827ec3251f7b1d456c73969a4b9154c496860af44cc2f6b46008c863450ae27820539682a7df05e14e959460cb09e6a48ea3135006ee6f0baac',
	keyEthAddress: '0xf7c5c7a2Beb1669638F238Ef40cE5C8d41d67D3B',
	testPricing,
}
