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

/**
 * TOM Generator State API — Proxy to backend-compliance (Python/FastAPI)
 *
 * GET /api/sdk/v1/tom-generator/state?tenantId=xxx - Load TOM generator state
 * POST /api/sdk/v1/tom-generator/state - Save TOM generator state
 * DELETE /api/sdk/v1/tom-generator/state?tenantId=xxx - Clear state
 */

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

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const tenantId = searchParams.get('tenantId')

    const url = tenantId
      ? `${BACKEND_URL}/api/compliance/tom/state?tenant_id=${encodeURIComponent(tenantId)}`
      : `${BACKEND_URL}/api/compliance/tom/state`

    const res = await fetch(url, {
      headers: { 'Content-Type': 'application/json' },
    })

    const data = await res.json()
    return NextResponse.json(data, { status: res.status })
  } catch (error) {
    console.error('Failed to load TOM generator state:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to load state' },
      { status: 500 }
    )
  }
}

export async function POST(request: NextRequest) {
  try {
    const body = await request.json()
    const { tenantId, state, version } = body

    if (!tenantId) {
      return NextResponse.json(
        { success: false, error: 'tenantId is required' },
        { status: 400 }
      )
    }

    if (!state) {
      return NextResponse.json(
        { success: false, error: 'state is required' },
        { status: 400 }
      )
    }

    const res = await fetch(`${BACKEND_URL}/api/compliance/tom/state`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        tenant_id: tenantId,
        state,
        version,
      }),
    })

    const data = await res.json()
    return NextResponse.json(data, { status: res.status })
  } catch (error) {
    console.error('Failed to save TOM generator state:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to save state' },
      { status: 500 }
    )
  }
}

export async function DELETE(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url)
    const tenantId = searchParams.get('tenantId')

    if (!tenantId) {
      return NextResponse.json(
        { success: false, error: 'tenantId is required' },
        { status: 400 }
      )
    }

    const res = await fetch(
      `${BACKEND_URL}/api/compliance/tom/state?tenant_id=${encodeURIComponent(tenantId)}`,
      {
        method: 'DELETE',
        headers: { 'Content-Type': 'application/json' },
      }
    )

    const data = await res.json()
    return NextResponse.json(data, { status: res.status })
  } catch (error) {
    console.error('Failed to delete TOM generator state:', error)
    return NextResponse.json(
      { success: false, error: 'Failed to delete state' },
      { status: 500 }
    )
  }
}

export async function OPTIONS() {
  return NextResponse.json(
    { status: 'ok' },
    {
      headers: {
        Allow: 'GET, POST, DELETE, OPTIONS',
      },
    }
  )
}
