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

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

/**
 * Proxy: GET /api/sdk/v1/modules/:moduleId → Backend GET /api/modules/:moduleId
 */
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ moduleId: string }> }
) {
  try {
    const { moduleId } = await params

    const response = await fetch(
      `${BACKEND_URL}/api/compliance/modules/${encodeURIComponent(moduleId)}`,
      {
        method: 'GET',
        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 }
      )
    }

    const data = await response.json()
    return NextResponse.json(data)
  } catch (error) {
    console.error('Failed to fetch module:', error)
    return NextResponse.json(
      { error: 'Failed to connect to backend' },
      { status: 503 }
    )
  }
}
