import crypto from 'crypto'

export function generateCompanyApiKey() {
  const secret = crypto.randomBytes(32).toString('base64url')
  const prefix = `rdg_${crypto.randomBytes(6).toString('hex')}`
  const rawKey = `${prefix}_${secret}`
  return { rawKey, prefix, keyHash: hashApiKey(rawKey) }
}

export function getApiKeyPrefix(rawKey: string) {
  const parts = rawKey.split('_')
  if (parts.length < 3) return null
  return `${parts[0]}_${parts[1]}`
}

export function hashApiKey(rawKey: string) {
  return crypto.createHash('sha256').update(rawKey).digest('hex')
}

export function timingSafeEqualHex(a: string, b: string) {
  const left = Buffer.from(a, 'hex')
  const right = Buffer.from(b, 'hex')
  if (left.length !== right.length) return false
  return crypto.timingSafeEqual(left, right)
}
