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

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

/**
 * Proxy: GET /api/sdk/v1/import → Backend GET /api/v1/import
 * Lists imported documents for the current tenant.
 */
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const queryString = searchParams.toString()
    const url = `${BACKEND_URL}/api/v1/import${queryString ? `?${queryString}` : ''}`

    const response = await fetch(url, {
      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 imported documents:', error)
    return NextResponse.json(
      { error: 'Failed to connect to backend' },
      { status: 503 }
    )
  }
}

/**
 * Proxy: POST /api/sdk/v1/import → Backend POST /api/v1/import/analyze
 * Uploads a document for gap analysis. Forwards multipart/form-data.
 */
export async function POST(request: NextRequest) {
  try {
    const contentType = request.headers.get('content-type') || ''
    const url = `${BACKEND_URL}/api/v1/import/analyze`

    let body: BodyInit
    const headers: Record<string, string> = {}

    if (contentType.includes('multipart/form-data')) {
      body = await request.arrayBuffer()
      headers['Content-Type'] = contentType
    } else {
      body = await request.text()
      headers['Content-Type'] = 'application/json'
    }

    if (request.headers.get('X-Tenant-ID')) {
      headers['X-Tenant-ID'] = request.headers.get('X-Tenant-ID') as string
    }

    const response = await fetch(url, {
      method: 'POST',
      headers,
      body,
    })

    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 upload document for import analysis:', error)
    return NextResponse.json(
      { error: 'Failed to connect to backend' },
      { status: 503 }
    )
  }
}
