import { req } from '@/common/js/index.js';

const AUTH_PREFIX = '/newApi/doctor-wx-auth';

function unwrapResult(res) {
	if (!res) return null;
	if (res.code === 0 && res.result !== undefined) return res.result;
	return res.result != null ? res.result : res.data;
}

function doctorAuthRequest(options) {
	return req.request({
		...options,
		url: `${AUTH_PREFIX}${options.url}`,
	}).then((res) => {
		const data = unwrapResult(res);
		const ok = res && res.code === 0;
		return { res, data, ok };
	});
}

export function sendDoctorWxCode(phone, password) {
	return req.request({
		url: `${AUTH_PREFIX}/send-verification-code`,
		method: 'POST',
		data: { phone, password },
		header: { isToken: false },
	});
}

export function doctorWxLogin(payload) {
	return req.request({
		url: `${AUTH_PREFIX}/login`,
		method: 'POST',
		data: payload,
		header: { isToken: false },
	});
}

export function getDoctorWxSiblingAccounts() {
	return doctorAuthRequest({
		url: '/sibling-accounts',
		method: 'GET',
	});
}

export function switchDoctorWxAccount(payload) {
	return doctorAuthRequest({
		url: '/switch-account',
		method: 'POST',
		data: payload,
	});
}

export function getDoctorWxAuthConfig() {
	return req.request({
		url: `${AUTH_PREFIX}/config`,
		method: 'GET',
		header: { isToken: false },
	});
}

export function doctorWxLoginByWechat(payload) {
	return req.request({
		url: `${AUTH_PREFIX}/wx-login`,
		method: 'POST',
		data: payload,
		header: { isToken: false },
	});
}

export function getDoctorWxBindStatus() {
	return doctorAuthRequest({
		url: '/wx-bind-status',
		method: 'GET',
	});
}

export function bindDoctorWxWechat(code) {
	return doctorAuthRequest({
		url: '/bind-wechat',
		method: 'POST',
		data: { code },
	});
}
