import { existsSync } from 'node:fs'
import { getCotSslPaths, TRUSTSTORE_PASSWORD, COT_TLS_REQUIRED_MESSAGE, buildP12FromCertPath } from '../../utils/cotSsl.js'
import { requireAuth } from '../../utils/authHelpers.js'

export default defineEventHandler((event) => {
  requireAuth(event)
  const config = useRuntimeConfig()
  const paths = getCotSslPaths(config)
  if (!paths || !existsSync(paths.certPath)) {
    setResponseStatus(event, 404)
    return { error: `CoT server is not using TLS or cert not found. Trust store ${COT_TLS_REQUIRED_MESSAGE}` }
  }

  try {
    const p12 = buildP12FromCertPath(paths.certPath, TRUSTSTORE_PASSWORD)
    setHeader(event, 'Content-Type', 'application/x-pkcs12')
    setHeader(event, 'Content-Disposition', 'attachment; filename="kestrelos-cot-truststore.p12"')
    return p12
  }
  catch (err) {
    setResponseStatus(event, 500)
    return { error: 'Failed to build trust store.', detail: err?.message }
  }
})
