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

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

/**
 * Proxy: GET /api/sdk/v1/compliance-scope → Backend GET /api/v1/compliance-scope
 * Retrieves the persisted scope decision for a tenant.
 */
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const tenantId = searchParams.get('tenant_id') || 'default'

    const response = await fetch(
      `${BACKEND_URL}/api/compliance/v1/compliance-scope?tenant_id=${encodeURIComponent(tenantId)}`,
      {
        headers: {
          'Content-Type': 'application/json',
          'X-Tenant-ID': tenantId,
        },
      }
    )

    if (!response.ok) {
      if (response.status === 404) {
        return NextResponse.json(null, { status: 404 })
      }
      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 compliance scope:', error)
    return NextResponse.json(
      { error: 'Failed to connect to backend' },
      { status: 503 }
    )
  }
}

/**
 * Proxy: POST /api/sdk/v1/compliance-scope → Backend POST /api/v1/compliance-scope
 * Persists the scope decision and answers.
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const tenantId = body.tenant_id || 'default'

    const response = await fetch(
      `${BACKEND_URL}/api/v1/compliance-scope?tenant_id=${encodeURIComponent(tenantId)}`,
      {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'X-Tenant-ID': tenantId,
        },
        body: JSON.stringify(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 save compliance scope:', error)
    return NextResponse.json(
      { error: 'Failed to connect to backend' },
      { status: 503 }
    )
  }
}
