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

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

function getIds(request: NextRequest, body?: Record<string, unknown>) {
  const { searchParams } = new URL(request.url)
  const tenantId = searchParams.get('tenant_id') || 'default'
  const projectId = searchParams.get('project_id') || (body?.project_id as string) || ''
  const qs = projectId
    ? `tenant_id=${encodeURIComponent(tenantId)}&project_id=${encodeURIComponent(projectId)}`
    : `tenant_id=${encodeURIComponent(tenantId)}`
  return { tenantId, projectId, qs }
}

/**
 * Proxy: GET /api/sdk/v1/company-profile → Backend GET /api/v1/company-profile
 */
export async function GET(request: NextRequest) {
  try {
    const { tenantId, qs } = getIds(request)

    const response = await fetch(
      `${BACKEND_URL}/api/v1/company-profile?${qs}`,
      {
        headers: {
          'X-Tenant-ID': tenantId,
        },
      }
    )

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

    const data = await response.json()
    return NextResponse.json(data)
  } catch (error) {
    console.error('Failed to fetch company profile:', error)
    return NextResponse.json(
      { error: 'Failed to connect to backend' },
      { status: 503 }
    )
  }
}

/**
 * Proxy: POST /api/sdk/v1/company-profile → Backend POST /api/v1/company-profile
 */
export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { tenantId, qs } = getIds(request, body)

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

    const data = await response.json()
    return NextResponse.json(data)
  } catch (error) {
    console.error('Failed to save company profile:', error)
    return NextResponse.json(
      { error: 'Failed to connect to backend' },
      { status: 503 }
    )
  }
}

/**
 * Proxy: DELETE /api/sdk/v1/company-profile → Backend DELETE /api/v1/company-profile
 * DSGVO Art. 17 Recht auf Löschung
 */
export async function DELETE(request: NextRequest) {
  try {
    const { tenantId, qs } = getIds(request)

    const response = await fetch(
      `${BACKEND_URL}/api/v1/company-profile?${qs}`,
      {
        method: 'DELETE',
        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 delete company profile:', error)
    return NextResponse.json(
      { error: 'Failed to connect to backend' },
      { status: 503 }
    )
  }
}

/**
 * Proxy: PATCH /api/sdk/v1/company-profile → Backend PATCH /api/v1/company-profile
 * Partial updates for individual fields
 */
export async function PATCH(request: NextRequest) {
  try {
    const body = await request.json()
    const { tenantId, qs } = getIds(request, body)

    const response = await fetch(
      `${BACKEND_URL}/api/v1/company-profile?${qs}`,
      {
        method: 'PATCH',
        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 }
      )
    }

    const data = await response.json()
    return NextResponse.json(data)
  } catch (error) {
    console.error('Failed to patch company profile:', error)
    return NextResponse.json(
      { error: 'Failed to connect to backend' },
      { status: 503 }
    )
  }
}
