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

const SDK_BASE_URL = process.env.SDK_BASE_URL || 'http://localhost:8085'

const DEFAULT_TENANT_ID = '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e'
const DEFAULT_USER_ID = 'admin'

async function proxyRequest(request: NextRequest, method: string) {
  try {
    const pathSegments = request.nextUrl.pathname.replace('/api/sdk/v1/ucca/obligations/', '')
    const targetUrl = `${SDK_BASE_URL}/sdk/v1/ucca/obligations/${pathSegments}${request.nextUrl.search}`

    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
      'X-Tenant-ID': request.headers.get('X-Tenant-ID') || DEFAULT_TENANT_ID,
      'X-User-ID': request.headers.get('X-User-ID') || DEFAULT_USER_ID,
    }

    const fetchOptions: RequestInit = { method, headers }
    if (method === 'POST' || method === 'PUT' || method === 'PATCH') {
      fetchOptions.body = await request.text()
    }

    const response = await fetch(targetUrl, fetchOptions)
    if (!response.ok) {
      const errorText = await response.text()
      return NextResponse.json({ error: 'SDK backend error', details: errorText }, { status: response.status })
    }

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

export async function GET(request: NextRequest) { return proxyRequest(request, 'GET') }
export async function POST(request: NextRequest) { return proxyRequest(request, 'POST') }
