import { eq }                         from "drizzle-orm"
import type { FastifyPluginAsyncZod } from "@fastify/type-provider-zod"
import { db }                          from "../db/index.js"
import { servers }                     from "../db/schema.js"
import { parseBgpSessions }            from "../services/bgp-parse-sessions.js"
import { MikrotikClient }              from "../services/mikrotik.js"
import { ServerIdParamSchema, type ServerIdParams }         from "../types/server.js"
import type { BgpSessionRead } from "../types/server.js"

const bgpRoutes: FastifyPluginAsyncZod = async (app) => {

  // GET /api/bgp/sessions/raw/:id — raw RouterOS response for a single server (debug)
  app.get("/bgp/sessions/raw/:id", { schema: { params: ServerIdParamSchema } }, async (req, reply) => {
    const params = req.params as ServerIdParams
    const server = db.select().from(servers).where(eq(servers.id, params.id)).limit(1).all()[0]
    if (!server) return reply.status(404).send({ error: "Server not found" })
    try {
      const client = MikrotikClient.fromServer(server)
      const raw    = await client.getBgpSessionsRaw()
      app.log.info({ serverId: server.id, host: server.host, raw }, "BGP raw response")
      return reply.send({ server: { id: server.id, host: server.host, name: server.name }, raw })
    } catch (err) {
      return reply.status(500).send({ error: String(err) })
    }
  })

  // GET /api/bgp/sessions — aggregate from ALL enabled servers
  app.get("/bgp/sessions", async (_req, reply) => {
    const allServers = db.select().from(servers).where(eq(servers.enabled, true)).all()

    const results: BgpSessionRead[][] = await Promise.all(
      allServers.map(async (server) => {
        try {
          const client = MikrotikClient.fromServer(server)
          const raw    = await client.getBgpSessions()
          return parseBgpSessions(server, raw)
        } catch {
          return []
        }
      }),
    )

    return reply.send(results.flat())
  })

  // GET /api/servers/:id/bgp/sessions — single server
  app.get("/servers/:id/bgp/sessions", { schema: { params: ServerIdParamSchema } }, async (req, reply) => {
    const params = req.params as ServerIdParams
    const server = db
      .select().from(servers)
      .where(eq(servers.id, params.id))
      .limit(1).all()[0]

    if (!server) return reply.status(404).send({ error: "Server not found" })

    try {
      const client = MikrotikClient.fromServer(server)
      const raw    = await client.getBgpSessions()
      return reply.send(parseBgpSessions(server, raw))
    } catch {
      return reply.send([])
    }
  })
}

export default bgpRoutes
