import { reactive } from "vue";
import { BaseService } from "./service/base";
import { useUserStore } from "./store/user";
import { storage } from "./utils";

export type PhoneAuthState = {
	dismissed: boolean;
	ready: boolean;
};

export function phoneAuthState(): PhoneAuthState {
	const host = globalThis as any;
	if (!host.__phoneAuthState) {
		host.__phoneAuthState = reactive({
			dismissed: false,
			ready: false,
		});
	}
	return host.__phoneAuthState;
}

function wxLoginCode() {
	return new Promise<string>((resolve) => {
		uni.login({
			provider: "weixin",
			success: (res) => resolve(res.code || ""),
			fail: () => resolve(""),
		});
	});
}

let pending: Promise<boolean> | null = null;

/**
 * 已授权过手机号的微信用户，再次打开时用 openid 换回登录态。
 */
export function miniAutoLogin(force = false) {
	if (pending && !force) {
		return pending;
	}
	const task = runMiniAutoLogin(force).finally(() => {
		if (pending === task) {
			pending = null;
		}
	});
	pending = task;
	return task;
}

async function runMiniAutoLogin(force = false) {
	const user = useUserStore();
	if (!force && user.token && user.info?.phone && !storage.isExpired("token")) {
		return true;
	}

	const code = await wxLoginCode();
	if (!code) {
		return false;
	}

	const res = await new BaseService("app/user/login").request({
		url: "/miniAuto",
		method: "POST",
		data: { code },
	});

	if (!res?.token) {
		return false;
	}

	user.setToken(res);
	user.set({
		...(user.info || {}),
		id: res.id,
		unionid: res.unionid,
		phone: res.phone,
		nickName: res.nickName || user.info?.nickName,
		avatarUrl: res.avatarUrl || user.info?.avatarUrl,
	});
	return true;
}
