/**
 * 登录记住密码存储工具
 *
 * 负责对登录账号与密码进行加密存储与读取
 *
 * @module utils/storage/remember-login
 */
import CryptoJS from 'crypto-js'
import { StorageKeyManager } from '@/utils/storage/storage-key-manager'

const ENCRYPT_KEY = import.meta.env.VITE_LOCK_ENCRYPT_KEY
const REMEMBER_LOGIN_STORE_ID = 'remember-login'

// 使用 StorageKeyManager 生成带版本的存储键，避免硬编码
const storageKeyManager = new StorageKeyManager()
const REMEMBER_LOGIN_KEY = storageKeyManager.getStorageKey(REMEMBER_LOGIN_STORE_ID)

export interface RememberLoginPayload {
  accountName: string
  phone: string
  password: string
}

/**
 * 保存加密后的登录信息
 */
export const saveRememberLogin = (payload: RememberLoginPayload) => {
  if (!payload.accountName || !payload.phone || !payload.password) return

  const encryptedPassword = CryptoJS.AES.encrypt(payload.password, ENCRYPT_KEY).toString()
  const data = {
    accountName: payload.accountName,
    phone: payload.phone,
    password: encryptedPassword,
    updatedAt: Date.now()
  }

  localStorage.setItem(REMEMBER_LOGIN_KEY, JSON.stringify(data))
}

/**
 * 读取并解密已保存的登录信息
 */
export const loadRememberLogin = (): RememberLoginPayload | null => {
  const storedValue = localStorage.getItem(REMEMBER_LOGIN_KEY)
  if (!storedValue) return null

  try {
    const parsed = JSON.parse(storedValue) as {
      accountName?: string
      phone?: string
      password?: string
    }
    if (!parsed.accountName || !parsed.phone || !parsed.password) {
      clearRememberLogin()
      return null
    }

    const decryptedPassword = CryptoJS.AES.decrypt(parsed.password, ENCRYPT_KEY).toString(
      CryptoJS.enc.Utf8
    )

    return {
      accountName: parsed.accountName,
      phone: parsed.phone,
      password: decryptedPassword
    }
  } catch (error) {
    console.warn('[Login] 解析记住密码数据失败:', error)
    clearRememberLogin()
    return null
  }
}

/**
 * 清除记住的登录信息
 */
export const clearRememberLogin = () => {
  localStorage.removeItem(REMEMBER_LOGIN_KEY)
}
