import type { FastifyInstance } from 'fastify'
import { Client } from 'ssh2'
import { loadSshHost, connectTarget } from '../ssh/connect.js'
import { collectHostMetrics } from '../ssh/metrics/index.js'

export async function metricsRoutes(app: FastifyInstance) {
  app.addHook('onRequest', app.authenticate)

  app.get('/api/integrations/:id/metrics', async (req, reply) => {
    const id = Number((req.params as { id: string }).id)
    const target = loadSshHost(id)
    if (!target) return reply.code(404).send({ error: 'SSH integration not found' })

    const jumpRef: { current: Client | null } = { current: null }
    const client = await new Promise<Client | null>((resolve) => {
      const { jumpConn } = connectTarget(
        target,
        (c) => resolve(c),
        () => {
          jumpConn?.end()
          resolve(null)
        },
      )
      jumpRef.current = jumpConn
    })

    if (!client) return reply.code(502).send({ error: 'Failed to connect to host' })

    try {
      const metrics = await collectHostMetrics(client)
      return metrics
    } finally {
      client.end()
      jumpRef.current?.end()
    }
  })
}
