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

const BACKEND_URL = process.env.CONSENT_BACKEND_URL || 'https://macmini:3007/api/sdk/v1/banner'
const TENANT_ID = process.env.CONSENT_TENANT_ID || '9282a473-5c95-4b3a-bf78-0ecc0ec71d3e'

export async function POST(req: NextRequest) {
  try {
    const data = await req.json()

    // Inject client IP for backend GeoIP resolution
    const ip = req.headers.get('x-forwarded-for')?.split(',')[0]?.trim()
      || req.headers.get('x-real-ip')
      || null
    if (ip) data.ip_address = ip

    const res = await fetch(`${BACKEND_URL}/consent`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Tenant-ID': TENANT_ID,
      },
      body: JSON.stringify(data),
    })

    const resBody = await res.text()
    return new NextResponse(resBody, {
      status: res.status,
      headers: { 'Content-Type': 'application/json' },
    })
  } catch (err) {
    console.error('Consent proxy error:', err)
    return NextResponse.json({ error: 'Consent service not reachable' }, { status: 503 })
  }
}
