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

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

export const loginByWechatCode = 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
		}),
		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;
};
