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

const BACKEND_URL = process.env.BACKEND_URL || 'http://backend-compliance:8002'

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const queryString = searchParams.toString()
    const url = `${BACKEND_URL}/api/v1/admin/policy-audit${queryString ? `?${queryString}` : ''}`

    const response = await fetch(url, {
      headers: {
        'Content-Type': 'application/json',
        ...(request.headers.get('X-Tenant-ID') && {
          'X-Tenant-ID': request.headers.get('X-Tenant-ID') as string,
        }),
      },
    })

    if (!response.ok) {
      const errorText = await response.text()
      return NextResponse.json({ error: 'Backend error', details: errorText }, { status: response.status })
    }

    return NextResponse.json(await response.json())
  } catch (error) {
    console.error('Failed to fetch policy audit:', error)
    return NextResponse.json({ error: 'Failed to connect to backend' }, { status: 503 })
  }
}
