import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { type NextRequest, NextResponse } from 'next/server'
import { boxUploadContract } from '@/lib/api/contracts/storage-transfer'
import { parseRequest } from '@/lib/api/server'
import { checkInternalAuth } from '@/lib/auth/hybrid'
import { generateRequestId } from '@/lib/core/utils/request'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import { processFilesToUserFiles, type RawFileInput } from '@/lib/uploads/utils/file-utils'
import { downloadServableFileFromStorage } from '@/lib/uploads/utils/file-utils.server'
import { docNotReadyResponse } from '@/lib/uploads/utils/servable-file-response'
import { assertToolFileAccess } from '@/app/api/files/authorization'

export const dynamic = 'force-dynamic'

const logger = createLogger('BoxUploadAPI')

export const POST = withRouteHandler(async (request: NextRequest) => {
  const requestId = generateRequestId()

  try {
    const authResult = await checkInternalAuth(request, { requireWorkflowId: false })

    if (!authResult.success || !authResult.userId) {
      logger.warn(`[${requestId}] Unauthorized Box upload attempt: ${authResult.error}`)
      return NextResponse.json(
        { success: false, error: authResult.error || 'Authentication required' },
        { status: 401 }
      )
    }

    logger.info(`[${requestId}] Authenticated Box upload request via ${authResult.authType}`)

    const parsed = await parseRequest(boxUploadContract, request, {})
    if (!parsed.success) return parsed.response
    const validatedData = parsed.data.body

    let fileBuffer: Buffer
    let fileName: string

    if (validatedData.file) {
      const userFiles = processFilesToUserFiles(
        [validatedData.file as RawFileInput],
        requestId,
        logger
      )

      if (userFiles.length === 0) {
        return NextResponse.json({ success: false, error: 'Invalid file input' }, { status: 400 })
      }

      const userFile = userFiles[0]
      logger.info(`[${requestId}] Downloading file: ${userFile.name} (${userFile.size} bytes)`)

      const denied = await assertToolFileAccess(userFile.key, authResult.userId, requestId, logger)
      if (denied) return denied
      try {
        const result = await downloadServableFileFromStorage(userFile, requestId, logger)
        fileBuffer = result.buffer
      } catch (error) {
        const notReady = docNotReadyResponse(error)
        if (notReady) return notReady
        return NextResponse.json(
          { success: false, error: getErrorMessage(error, 'Failed to download file') },
          { status: 500 }
        )
      }
      fileName = validatedData.fileName || userFile.name
    } else if (validatedData.fileContent) {
      logger.info(`[${requestId}] Using legacy base64 content input`)
      fileBuffer = Buffer.from(validatedData.fileContent, 'base64')
      fileName = validatedData.fileName || 'file'
    } else {
      return NextResponse.json({ success: false, error: 'File is required' }, { status: 400 })
    }

    logger.info(
      `[${requestId}] Uploading to Box folder ${validatedData.parentFolderId}: ${fileName} (${fileBuffer.length} bytes)`
    )

    const attributes = JSON.stringify({
      name: fileName,
      parent: { id: validatedData.parentFolderId },
    })

    const formData = new FormData()
    formData.append('attributes', attributes)
    formData.append(
      'file',
      new Blob([new Uint8Array(fileBuffer)], { type: 'application/octet-stream' }),
      fileName
    )

    const response = await fetch('https://upload.box.com/api/2.0/files/content', {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${validatedData.accessToken}`,
      },
      body: formData,
    })

    const data = await response.json()

    if (!response.ok) {
      const errorMessage = data.message || 'Failed to upload file'
      logger.error(`[${requestId}] Box API error:`, { status: response.status, data })
      return NextResponse.json({ success: false, error: errorMessage }, { status: response.status })
    }

    const file = data.entries?.[0]

    if (!file) {
      return NextResponse.json(
        { success: false, error: 'No file returned in upload response' },
        { status: 500 }
      )
    }

    logger.info(`[${requestId}] File uploaded successfully: ${file.name} (ID: ${file.id})`)

    return NextResponse.json({
      success: true,
      output: {
        id: file.id ?? '',
        name: file.name ?? '',
        size: file.size ?? 0,
        sha1: file.sha1 ?? null,
        createdAt: file.created_at ?? null,
        modifiedAt: file.modified_at ?? null,
        parentId: file.parent?.id ?? null,
        parentName: file.parent?.name ?? null,
      },
    })
  } catch (error) {
    logger.error(`[${requestId}] Unexpected error:`, error)
    return NextResponse.json(
      { success: false, error: getErrorMessage(error, 'Unknown error') },
      { status: 500 }
    )
  }
})
