import { Router, Request, Response } from 'express'
import tls from 'tls'
import { BaseApi } from './BaseApi.js'
import cors from 'cors'

const router = Router()
export default router

class CertificatesRoute extends BaseApi {
  async index(req: Request, res: Response): Promise<void> {
    const socket = req.socket as tls.TLSSocket
    const cert = socket.getPeerCertificate()

    let status: number
    let message: unknown
    if (socket.authorized) {
      status = 200
      message = {
        authenticated: true,
        name: cert.subject.CN,
        issuer: cert.issuer.CN,
      }
    } else if (cert.subject) {
      status = 403
      message = {
        authenticated: false,
        name: cert.subject.CN,
        issuer: cert.issuer.CN,
      }
    } else {
      status = 401
      message = {
        authenticated: false,
      }
    }
    res.writeHead(status, {
      'Content-Type': 'application/json; charset=UTF-8',
    })
    res.end(JSON.stringify(message))
  }
}

const api = new CertificatesRoute()
api.setCors(router)
const checkCorsFn = api._processCors
router.get('/', cors(checkCorsFn), api.index.bind(api))
