import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'crypto'

/** 加密文本前缀标记 */
const PREFIX = 'enc:v1:'

function keyFromPassword(pwd: string): Buffer {
  return createHash('sha256').update(pwd, 'utf8').digest()
}

/** 用密码加密文本；pwd 为空时原样返回 */
export function encryptText(text: string, pwd: string): string {
  if (!pwd || !text) return text
  const iv = randomBytes(12)
  const cipher = createCipheriv('aes-256-gcm', keyFromPassword(pwd), iv)
  const enc = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()])
  const tag = cipher.getAuthTag()
  return PREFIX + Buffer.concat([iv, tag, enc]).toString('base64')
}

/**
 * 用密码解密文本。
 * - 非加密文本原样返回
 * - 密码错误返回 null（调用方应据此提示）
 */
export function decryptText(text: string, pwd: string): string | null {
  if (!text || !text.startsWith(PREFIX)) return text
  try {
    const raw = Buffer.from(text.slice(PREFIX.length), 'base64')
    const iv = raw.subarray(0, 12)
    const tag = raw.subarray(12, 28)
    const data = raw.subarray(28)
    const decipher = createDecipheriv('aes-256-gcm', keyFromPassword(pwd), iv)
    decipher.setAuthTag(tag)
    return Buffer.concat([decipher.update(data), decipher.final()]).toString('utf8')
  } catch {
    return null
  }
}
