import { get } from '@/utils/request.js'
import JSEncrypt from '@/js_sdk/mark-jsencrypt/mark-jsencrypt/mark-jsencrypt.js'

let cachedPublicKey = ''

/**
 * 将接口返回的公钥转为 JSEncrypt 可用格式
 * @param {string} publicKey
 */
function normalizePublicKey(publicKey) {
	if (!publicKey) return ''
	const key = String(publicKey).trim().replace(/\\n/g, '\n')
	if (key.includes('BEGIN PUBLIC KEY')) {
		return key
	}
	const raw = key.replace(/\s/g, '')
	const lines = raw.match(/.{1,64}/g) || [raw]
	return `-----BEGIN PUBLIC KEY-----\n${lines.join('\n')}\n-----END PUBLIC KEY-----`
}

/**
 * 获取 RSA 公钥（带内存缓存）
 */
export function fetchPasswordPublicKey(options = {}) {
	if (cachedPublicKey && !options.refresh) {
		return Promise.resolve(cachedPublicKey)
	}
	return get('/auth/password/public-key', null, { auth: false, ...options }).then((res) => {
		const key = (res && res.publicKey) || ''
		if (!key) {
			return Promise.reject(new Error('RSA 公钥为空'))
		}
		cachedPublicKey = normalizePublicKey(key)
		return cachedPublicKey
	})
}

/**
 * RSA 加密密码，返回 Base64 密文
 * @param {string} plainPassword
 * @param {string} [publicKey]
 */
export function encryptPassword(plainPassword, publicKey) {
	const encryptor = new JSEncrypt()
	const key = publicKey || cachedPublicKey
	if (!key) {
		throw new Error('RSA 公钥未加载')
	}
	encryptor.setPublicKey(key)
	const encrypted = encryptor.encrypt(String(plainPassword))
	if (!encrypted) {
		throw new Error('密码加密失败')
	}
	return encrypted
}

/**
 * 拉取公钥并加密密码
 * @param {string} plainPassword
 */
export async function encryptPasswordWithFetch(plainPassword) {
	const publicKey = await fetchPasswordPublicKey()
	return encryptPassword(plainPassword, publicKey)
}

export function clearPasswordPublicKeyCache() {
	cachedPublicKey = ''
}
