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

const SDK_URL = process.env.SDK_URL || 'http://ai-compliance-sdk:8090'

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const endpoint = searchParams.get('endpoint') || 'controls'
    const tenantId = request.headers.get('x-tenant-id') || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e'

    let path: string
    switch (endpoint) {
      case 'controls':
        const domain = searchParams.get('domain') || ''
        path = `/sdk/v1/payment-compliance/controls${domain ? `?domain=${domain}` : ''}`
        break
      case 'assessments':
        path = '/sdk/v1/payment-compliance/assessments'
        break
      default:
        path = '/sdk/v1/payment-compliance/controls'
    }

    const resp = await fetch(`${SDK_URL}${path}`, {
      headers: { 'X-Tenant-ID': tenantId },
    })
    const data = await resp.json()
    return NextResponse.json(data)
  } catch (err) {
    return NextResponse.json({ error: 'Failed to fetch' }, { status: 500 })
  }
}

export async function POST(request: NextRequest) {
  try {
    const tenantId = request.headers.get('x-tenant-id') || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e'
    const body = await request.json()
    const resp = await fetch(`${SDK_URL}/sdk/v1/payment-compliance/assessments`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json', 'X-Tenant-ID': tenantId },
      body: JSON.stringify(body),
    })
    const data = await resp.json()
    return NextResponse.json(data, { status: resp.status })
  } catch (err) {
    return NextResponse.json({ error: 'Failed to create' }, { status: 500 })
  }
}
