/**
 * GPU Admin API Route - Secure Proxy
 *
 * Der vast.ai API-Key wird serverseitig aus der Umgebungsvariable geladen
 * und niemals an den Client gesendet.
 */

import { NextRequest, NextResponse } from 'next/server'

// API Key für Backend-Authentifizierung (serverseitig, niemals im Client!)
// CONTROL_API_KEY ist der Backend-API-Key, VAST_API_KEY ist für vast.ai direkt
const BACKEND_API_KEY = process.env.CONTROL_API_KEY || process.env.VAST_API_KEY

// Backend URL
const BACKEND_URL = process.env.BACKEND_URL || 'http://localhost:8000'

export async function GET(request: NextRequest) {
  if (!BACKEND_API_KEY) {
    return NextResponse.json(
      { error: 'CONTROL_API_KEY nicht konfiguriert' },
      { status: 500 }
    )
  }

  try {
    const response = await fetch(`${BACKEND_URL}/infra/vast/status`, {
      headers: {
        'X-API-Key': BACKEND_API_KEY,
      },
    })

    const data = await response.json()
    return NextResponse.json(data, { status: response.status })
  } catch (error) {
    console.error('GPU Status fetch error:', error)
    return NextResponse.json(
      { error: 'Backend nicht erreichbar', status: 'error' },
      { status: 503 }
    )
  }
}

export async function POST(request: NextRequest) {
  if (!BACKEND_API_KEY) {
    return NextResponse.json(
      { error: 'CONTROL_API_KEY nicht konfiguriert' },
      { status: 500 }
    )
  }

  try {
    const body = await request.json()
    const action = body.action // 'on' or 'off'

    if (!['on', 'off'].includes(action)) {
      return NextResponse.json(
        { error: 'Ungültige Aktion' },
        { status: 400 }
      )
    }

    const endpoint = action === 'on' ? '/infra/vast/power/on' : '/infra/vast/power/off'

    const response = await fetch(`${BACKEND_URL}${endpoint}`, {
      method: 'POST',
      headers: {
        'X-API-Key': BACKEND_API_KEY,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({}),
    })

    const data = await response.json()
    return NextResponse.json(data, { status: response.status })
  } catch (error) {
    console.error('GPU Power action error:', error)
    return NextResponse.json(
      { error: 'Backend nicht erreichbar' },
      { status: 503 }
    )
  }
}
