import Fastify from 'fastify'
import { getDatabase } from '../lib/db'
import { hijackAlertsRoutes } from '../routes/hijack-alerts'
import { pdfExportRoutes } from '../routes/pdf-export'
import { aspaAdoptionRoutes } from '../routes/aspa-adoption'
import { bgpCommunitiesRoutes } from '../features/bgp-communities/routes'
import { irrAuditRoutes } from '../features/irr-audit/routes'
import { assetExpandRoutes } from '../features/asset-expand/routes'
import { rpkiHistoryRoutes } from '../features/rpki-history/routes'
import { aspathRoutes } from '../features/aspath/routes'
import { ixMatrixRoutes } from '../features/ix-matrix/routes'
import { lookingGlassRoutes } from '../features/looking-glass/routes'
import { prefixChangesRoutes } from '../features/prefix-changes/routes'
import { submarineCablesRoutes } from '../features/submarine-cables/routes'
import { globalInfraRoutes } from '../features/global-infra/routes'
import { changelogRoutes } from '../features/changelog/routes'
import { ribRoutes } from '../features/rib/routes'
import { hijackSubscribeRoutes } from '../features/hijack-subscribe/routes'

export async function createApiServer(port: number = 3100) {
  const fastify = Fastify({
    logger: {
      level: process.env.LOG_LEVEL ?? 'info',
    },
  })

  // Initialize routes
  await fastify.register(hijackAlertsRoutes, { prefix: '/api' })
  await fastify.register(pdfExportRoutes, { prefix: '/api' })
  await fastify.register(aspaAdoptionRoutes, { prefix: '/api' })
  await fastify.register(bgpCommunitiesRoutes, { prefix: '/api' })
  await fastify.register(irrAuditRoutes, { prefix: '/api' })
  await fastify.register(assetExpandRoutes, { prefix: '/api' })
  await fastify.register(rpkiHistoryRoutes, { prefix: '/api' })
  await fastify.register(aspathRoutes, { prefix: '/api' })
  await fastify.register(ixMatrixRoutes, { prefix: '/api' })
  await fastify.register(lookingGlassRoutes, { prefix: '/api' })
  await fastify.register(prefixChangesRoutes, { prefix: '/api' })
  await fastify.register(submarineCablesRoutes, { prefix: '/api' })
  await fastify.register(globalInfraRoutes, { prefix: '/api' })
  await fastify.register(changelogRoutes)
  await fastify.register(ribRoutes, { prefix: '/api' })
  await fastify.register(hijackSubscribeRoutes, { prefix: '/api' })

  // Health check endpoint
  fastify.get('/health', async () => {
    try {
      const db = getDatabase()
      await db.query('SELECT 1')
      return { status: 'ok', timestamp: new Date().toISOString() }
    } catch (error) {
      return { status: 'error', error: error instanceof Error ? error.message : 'Unknown error' }
    }
  })

  // Root endpoint
  fastify.get('/', async () => {
    return {
      name: 'PeerCortex API',
      version: '1.0.0',
      features: ['hijack-alerts', 'pdf-export', 'aspa-adoption-tracker', 'bgp-communities', 'irr-audit', 'asset-expand', 'rpki-history', 'aspath', 'ix-matrix', 'looking-glass', 'prefix-changes', 'submarine-cables', 'global-infra', 'changelog', 'rib', 'hijack-subscribe'],
      docs: 'https://peercortex.org/docs',
    }
  })

  return fastify
}

export async function startApiServer(port: number = 3100): Promise<void> {
  const server = await createApiServer(port)

  try {
    await server.listen({ port, host: process.env.API_HOST ?? '0.0.0.0' })
    console.log(`[API Server] Listening on http://0.0.0.0:${port}`)
  } catch (error) {
    console.error('[API Server] Failed to start:', error)
    process.exit(1)
  }
}
