/**
 * PEM helpers shared by the native enroll (enroll/pair.ts) and renew (certs/rotation.ts) paths.
 *
 * The control-plane returns the frp-client leaf + CA chain as base64-encoded DER (cert as a string,
 * caChain as a string[]); the keystore + frpc need PEM files. `derBase64ToPem` wraps a base64 DER body
 * back into CERTIFICATE armor at 64 columns.
 */

/** base64(DER) → PEM (CERTIFICATE armor, 64-col wrapped). */
export function derBase64ToPem(derBase64: string, label = 'CERTIFICATE'): string {
  const body = derBase64.replace(/\s+/g, '')
  const lines = body.match(/.{1,64}/g) ?? []
  return `-----BEGIN ${label}-----\n${lines.join('\n')}\n-----END ${label}-----\n`
}

/**
 * Normalize a control-plane cert response ({cert: base64 DER, caChain: base64 DER[]}) to PEM strings
 * for the keystore. Throws if the shape is wrong. Shared by enroll + renew so both stay in lockstep.
 */
export function certResponseToPem(cert: unknown, caChain: unknown): { certPem: string; caChainPem: string } {
  if (
    typeof cert !== 'string' ||
    !Array.isArray(caChain) ||
    caChain.length === 0 ||
    !caChain.every((c) => typeof c === 'string')
  ) {
    throw new Error('cert response missing cert/caChain')
  }
  return {
    certPem: derBase64ToPem(cert),
    caChainPem: (caChain as string[]).map((c) => derBase64ToPem(c)).join(''),
  }
}
