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

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

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params

    const response = await fetch(`${BACKEND_URL}/api/v1/admin/operations/${encodeURIComponent(id)}`, {
      headers: {
        'Content-Type': 'application/json',
        ...(request.headers.get('X-Tenant-ID') && {
          'X-Tenant-ID': request.headers.get('X-Tenant-ID') as string,
        }),
      },
    })

    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 fetch operation:', error)
    return NextResponse.json({ error: 'Failed to connect to backend' }, { status: 503 })
  }
}

export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params
    const body = await request.json()

    const response = await fetch(`${BACKEND_URL}/api/v1/admin/operations/${encodeURIComponent(id)}`, {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json',
        ...(request.headers.get('X-Tenant-ID') && {
          'X-Tenant-ID': request.headers.get('X-Tenant-ID') as string,
        }),
      },
      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())
  } catch (error) {
    console.error('Failed to update operation:', error)
    return NextResponse.json({ error: 'Failed to connect to backend' }, { status: 503 })
  }
}

export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params

    const response = await fetch(`${BACKEND_URL}/api/v1/admin/operations/${encodeURIComponent(id)}`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json',
        ...(request.headers.get('X-Tenant-ID') && {
          'X-Tenant-ID': request.headers.get('X-Tenant-ID') as string,
        }),
      },
    })

    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 delete operation:', error)
    return NextResponse.json({ error: 'Failed to connect to backend' }, { status: 503 })
  }
}
