import { APP_CONFIG } from '@/config';
import { HttpStatusError, httpRequest, toFormUrlEncoded } from '@/utils/http';
import { postForm } from '@/utils/request';

export interface LoginResponse {
	code: number | string;
	msg?: string;
	data?: {
		token?: string;
		expires_in?: number;
	};
}

export type LoginPlatform = 'mp-weixin' | 'mp-alipay';

export const resolveLoginPlatform = (): LoginPlatform => {
	// #ifdef MP-ALIPAY
	return 'mp-alipay';
	// #endif

	// #ifdef MP-WEIXIN
	return 'mp-weixin';
	// #endif

	// #ifndef MP-WEIXIN
	// #ifndef MP-ALIPAY
	return 'mp-weixin';
	// #endif
	// #endif
};

/** 微信 code / 支付宝 authCode 都走同一登录接口 */
export const loginByCode = async (code: string) => {
	const response = await httpRequest<LoginResponse>({
		url: `${APP_CONFIG.API_BASE_URL}/user/v3/login.code`,
		method: 'POST',
		data: toFormUrlEncoded({
			code,
			app_id: APP_CONFIG.APP_ID,
			platform: resolveLoginPlatform()
		}),
		header: {
			'content-type': 'application/x-www-form-urlencoded'
		}
	});

	if (response.statusCode < 200 || response.statusCode >= 300) {
		throw new HttpStatusError('登录请求失败', response.statusCode, response.data);
	}

	return response.data;
};

/** @deprecated 使用 loginByCode */
export const loginByWechatCode = loginByCode;

export interface BindMobileResponse {
	code: number | string;
	msg?: string;
	data?: {
		code?: string;
		msg?: string;
		mobile?: string;
	};
}

/**
 * 支付宝手机号绑定。
 * encryptedData = my.getPhoneNumber 成功回调里 response.response（解密密文）
 * 需登录态：走 postForm，自动带 Authorization: Bearer <token>
 */
export const bindMobile = (encryptedData: string) => {
	return postForm<BindMobileResponse>('user/v1/bind.mobile', {
		encryptedData,
		app_id: APP_CONFIG.APP_ID,
		platform: resolveLoginPlatform()
	});
};
