// #ifdef H5
import Adjust from "@adjustcom/adjust-web-sdk"
// #endif

import { useAppStore } from "@/store/useAppStore"
import { requestUserAdid } from '@/api/user.js'

export const setupAdjust = () => {
	// #ifdef H5
	if (!process.env.ADJUST_KEY) {
		return
	}
	Adjust.initSdk({
		appToken: process.env.ADJUST_KEY,
		environment: 'production',
		// logLevel: 'verbose',
		// environment: process.env.NODE_ENV === 'production' ? 'production' : 'sandbox'
		attributionCallback: (e, attribution) => {
			console.log('Adjust info callback:', process.env.ADJUST_KEY, attribution)
			const appStore = useAppStore()
			appStore.adjustAdid = attribution.adid
		}
	})
	getAdjustAdid()
	// #endif
}

export const getAdjustAdid = () => {
	return new Promise((resolve) => {
		if (!process.env.ADJUST_KEY) {
			resolve()
			return
		}
		const appStore = useAppStore()
		if (appStore.adjustAdid) {
			resolve()
			return
		}
		let count = 0
		const timer = setInterval(() => {
			const attribution = Adjust.getAttribution()
			console.log('Adjust info:', process.env.ADJUST_KEY, attribution)
			
			if (attribution && attribution.adid) {
				resolve()
				clearInterval(timer)
				appStore.adjustAdid = attribution.adid
				return
			}

			count++
			if (count > 30) {
				resolve()
				clearInterval(timer)
			}
		}, 500)
	})
}

export const reportAdjustAdid = async () => {
	if (!process.env.ADJUST_KEY) {
		return
	}
	// await getAdjustAdid()
	// const { code } = await requestUserAdid()
}

