/**
 * Phoenix API Railing — REST routes for Infra/VE/Health proxy and tenant-scoped Client API.
 * When PHOENIX_RAILING_URL is set, /api/v1/infra/*, /api/v1/ve/*, /api/v1/health/* proxy to it.
 * /api/v1/tenants/me/* are tenant-scoped (from tenantContext).
 */

import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify'

const RAILING_URL = (process.env.PHOENIX_RAILING_URL || '').replace(/\/$/, '')
const RAILING_API_KEY = process.env.PHOENIX_RAILING_API_KEY || ''

async function proxyToRailing(
  request: FastifyRequest<{ Params: Record<string, string>; Querystring: Record<string, string> }>,
  reply: FastifyReply,
  path: string
) {
  if (!RAILING_URL) {
    return reply.status(503).send({
      error: 'Phoenix railing not configured',
      message: 'Set PHOENIX_RAILING_URL to the Phoenix Deploy API or Phoenix API base URL',
    })
  }
  const qs = new URLSearchParams(request.query as Record<string, string>).toString()
  const url = `${RAILING_URL}${path}${qs ? `?${qs}` : ''}`
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    ...(request.headers['content-type'] && { 'Content-Type': request.headers['content-type'] }),
  }
  if (RAILING_API_KEY) headers['Authorization'] = `Bearer ${RAILING_API_KEY}`
  else if (request.headers.authorization) headers['Authorization'] = request.headers.authorization
  try {
    const res = await fetch(url, {
      method: request.method,
      headers,
      body: request.method !== 'GET' && request.body ? JSON.stringify(request.body) : undefined,
    })
    const data = await res.json().catch(() => ({}))
    return reply.status(res.status).send(data)
  } catch (err: any) {
    return reply.status(502).send({ error: err?.message || 'Railing proxy failed' })
  }
}

export async function registerPhoenixRailingRoutes(fastify: FastifyInstance) {
  if (RAILING_URL) {
    fastify.get('/api/v1/infra/nodes', async (request, reply) => proxyToRailing(request, reply, '/api/v1/infra/nodes'))
    fastify.get('/api/v1/infra/storage', async (request, reply) => proxyToRailing(request, reply, '/api/v1/infra/storage'))
    fastify.get('/api/v1/ve/vms', async (request, reply) => proxyToRailing(request, reply, '/api/v1/ve/vms'))
    fastify.get('/api/v1/ve/vms/:node/:vmid/status', async (request, reply) => {
      const { node, vmid } = (request as any).params
      return proxyToRailing(request, reply, `/api/v1/ve/vms/${node}/${vmid}/status`)
    })
    fastify.get('/api/v1/health/metrics', async (request, reply) => proxyToRailing(request, reply, '/api/v1/health/metrics'))
    fastify.get('/api/v1/health/alerts', async (request, reply) => proxyToRailing(request, reply, '/api/v1/health/alerts'))
    fastify.get('/api/v1/health/summary', async (request, reply) => proxyToRailing(request, reply, '/api/v1/health/summary'))
    fastify.post('/api/v1/ve/vms/:node/:vmid/start', async (request, reply) => {
      const { node, vmid } = (request as any).params
      return proxyToRailing(request, reply, `/api/v1/ve/vms/${node}/${vmid}/start`)
    })
    fastify.post('/api/v1/ve/vms/:node/:vmid/stop', async (request, reply) => {
      const { node, vmid } = (request as any).params
      return proxyToRailing(request, reply, `/api/v1/ve/vms/${node}/${vmid}/stop`)
    })
    fastify.post('/api/v1/ve/vms/:node/:vmid/reboot', async (request, reply) => {
      const { node, vmid } = (request as any).params
      return proxyToRailing(request, reply, `/api/v1/ve/vms/${node}/${vmid}/reboot`)
    })
  }

  fastify.get('/api/v1/tenants/me/resources', async (request, reply) => {
    const tenantContext = (request as any).tenantContext
    if (!tenantContext?.tenantId) {
      return reply.status(401).send({ error: 'Tenant context required', message: 'Use API key or JWT with tenant scope' })
    }
    const db = (await import('../db/index.js')).getDb()
    const result = await db.query(
      'SELECT id, name, resource_type, provider, provider_id, site_id, metadata, created_at FROM resource_inventory WHERE tenant_id = $1 ORDER BY created_at DESC',
      [tenantContext.tenantId]
    )
    return reply.send({ resources: result.rows, tenantId: tenantContext.tenantId })
  })

  fastify.get('/api/v1/tenants/me/health', async (request, reply) => {
    const tenantContext = (request as any).tenantContext
    if (!tenantContext?.tenantId) {
      return reply.status(401).send({ error: 'Tenant context required' })
    }
    if (RAILING_URL) {
      return proxyToRailing(request, reply, '/api/v1/health/summary')
    }
    return reply.send({
      tenantId: tenantContext.tenantId,
      status: 'unknown',
      updated_at: new Date().toISOString(),
      message: 'Set PHOENIX_RAILING_URL for full health summary',
    })
  })
}
