import { get, post, setToken } from '@/utils/request.js'

/**
 * 发送登录验证码
 * @param {{ mobile: string, userType: 'enterprise' | 'worker' }} data
 */
export function sendLoginSmsCode(data) {
	return post('/auth/sms/send', data, { auth: false })
}

/**
 * 短信验证码登录
 * @param {{ mobile: string, code: string, userType: 'enterprise' | 'worker' }} data
 */
export function loginBySms(data) {
	return post('/auth/sms/login', data, { auth: false }).then((res) => {
		if (res && res.token) {
			setToken(res.token)
		}
		return res
	})
}

/**
 * 获取 RSA 公钥
 */
export function getPasswordPublicKey(options = {}) {
	return get('/auth/password/public-key', null, { auth: false, ...options })
}

/**
 * 账密登录
 * @param {{ account: string, encryptedPassword: string }} data
 */
export function loginByPassword(data) {
	return post('/auth/password/login', data, { auth: false }).then((res) => {
		if (res && res.token) {
			setToken(res.token)
		}
		return res
	})
}

/**
 * 短信验证码重置密码
 * @param {{
 *   mobile: string,
 *   code: string,
 *   encryptedPassword: string,
 *   encryptedConfirmPassword: string
 * }} data
 */
export function resetPasswordBySms(data) {
	return post('/auth/password/reset', data, { auth: false })
}

/**
 * 查询是否已设置登录密码（需 JWT）
 * @returns {Promise<{ passwordSet: boolean, usernameMask?: string }>}
 */
export function getPasswordStatus(options = {}) {
	return get('/auth/password/status', null, options)
}

/**
 * 设置或修改登录密码（需 JWT）
 * @param {{
 *   username?: string,
 *   encryptedPassword: string,
 *   encryptedConfirmPassword: string,
 *   encryptedOldPassword?: string
 * }} data
 */
export function setLoginPassword(data) {
	return post('/auth/password/set', data)
}
