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

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

/**
 * Proxy: GET /api/sdk/v1/projects → Backend GET /api/compliance/v1/projects
 */
export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const tenantId = searchParams.get('tenant_id') || request.headers.get('X-Tenant-ID') || ''
    const includeArchived = searchParams.get('include_archived') || 'false'

    const response = await fetch(
      `${BACKEND_URL}/api/compliance/v1/projects?tenant_id=${encodeURIComponent(tenantId)}&include_archived=${includeArchived}`,
      {
        headers: { 'X-Tenant-ID': tenantId },
      }
    )

    if (!response.ok) {
      const errorText = await response.text()
      return NextResponse.json(
        { error: 'Backend error', details: errorText },
        { status: response.status }
      )
    }

    return NextResponse.json(await response.json())
  } catch (error) {
    console.error('Failed to list projects:', error)
    return NextResponse.json(
      { error: 'Failed to connect to backend' },
      { status: 503 }
    )
  }
}

/**
 * Proxy: POST /api/sdk/v1/projects → Backend POST /api/compliance/v1/projects
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const tenantId = body.tenant_id || request.headers.get('X-Tenant-ID') || ''

    const response = await fetch(
      `${BACKEND_URL}/api/compliance/v1/projects?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 }
      )
    }

    return NextResponse.json(await response.json(), { status: 201 })
  } catch (error) {
    console.error('Failed to create project:', error)
    return NextResponse.json(
      { error: 'Failed to connect to backend' },
      { status: 503 }
    )
  }
}
