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

const testPricing = async (
	params: IActivDirectSearchAssetParams,
): Promise<CONTRACT_INTERFACES.IPrice> => {
	// console.log('testPricing [Alpaca] (params)', params);

	let headers = {
		Accept: 'application/json',
		'Content-Type': 'application/json',
		'User-Agent': 'Request-Promise',
		'APCA-API-KEY-ID': params.key,
		'APCA-API-SECRET-KEY': params.secret,
	}

	const requestRecipe = {
		url: 'https://api.ixily.io/v1/proxy',
		method: 'POST',
		body: JSON.stringify({
			url:
				'https://data.alpaca.markets/v2/stocks/snapshots?symbols=' +
				params.symbol,
			method: 'GET',
			headers,
		}),
		headers,
	}

	let data = await fetch(
		requestRecipe.url,
		requestRecipe as unknown as RequestInit,
	).then((res) => res.json())

	if (data === undefined || data === null) {
		throw new Error('Data not found')
	}

	data = data[params.symbol]['latestQuote']

	const ask = parseFloat(data.ap)
	const bid = parseFloat(data.bp)
	let globalPrice = (ask + bid) / 2
	const askAfterDot = ask.toString().split('.')
	let askDecimals = 0
	if (askAfterDot.length > 1) {
		askDecimals = askAfterDot[1].length
	}
	const bidAfterDot = bid.toString().split('.')
	let bidDecimals = 0
	if (bidAfterDot.length > 1) {
		bidDecimals = bidAfterDot[1].length
	}
	const decimals = Math.max(askDecimals, bidDecimals)
	globalPrice = parseFloat(globalPrice.toFixed(decimals))
	const timestamp = Date.now()
	const priceObj: CONTRACT_INTERFACES.IPrice = {
		ask,
		bid,
		globalPrice,
		provider: 'Alpaca',
		symbol: params.symbol,
		timestamp,
	}
	return priceObj
}

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