import { createLogger } from '@sim/logger'
import { getErrorMessage } from '@sim/utils/errors'
import { generateId } from '@sim/utils/id'
import { type NextRequest, NextResponse } from 'next/server'
import { mongodbQueryContract } from '@/lib/api/contracts/tools/databases/mongodb'
import { parseToolRequest } from '@/lib/api/server'
import { checkInternalAuth } from '@/lib/auth/hybrid'
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
import {
  createMongoDBConnection,
  sanitizeCollectionName,
  validateFilter,
} from '@/app/api/tools/mongodb/utils'

const logger = createLogger('MongoDBQueryAPI')

export const POST = withRouteHandler(async (request: NextRequest) => {
  const requestId = generateId().slice(0, 8)
  let client = null

  const auth = await checkInternalAuth(request)
  if (!auth.success || !auth.userId) {
    logger.warn(`[${requestId}] Unauthorized MongoDB query attempt`)
    return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
  }

  try {
    const parsed = await parseToolRequest(mongodbQueryContract, request, { logger })
    if (!parsed.success) return parsed.response
    const params = parsed.data.body

    logger.info(
      `[${requestId}] Executing MongoDB query on ${params.host}:${params.port}/${params.database}.${params.collection}`
    )

    const sanitizedCollection = sanitizeCollectionName(params.collection)

    let filter = {}
    if (params.query?.trim()) {
      const validation = validateFilter(params.query)
      if (!validation.isValid) {
        logger.warn(`[${requestId}] Filter validation failed: ${validation.error}`)
        return NextResponse.json(
          { error: `Filter validation failed: ${validation.error}` },
          { status: 400 }
        )
      }
      filter = JSON.parse(params.query)
    }

    let sortCriteria = {}
    if (params.sort?.trim()) {
      try {
        sortCriteria = JSON.parse(params.sort)
      } catch (error) {
        logger.warn(`[${requestId}] Invalid sort JSON: ${params.sort}`)
        return NextResponse.json({ error: 'Invalid JSON format in sort criteria' }, { status: 400 })
      }
    }

    client = await createMongoDBConnection({
      host: params.host,
      port: params.port,
      database: params.database,
      username: params.username,
      password: params.password,
      authSource: params.authSource,
      ssl: params.ssl,
    })

    const db = client.db(params.database)
    const coll = db.collection(sanitizedCollection)

    let cursor = coll.find(filter)

    if (Object.keys(sortCriteria).length > 0) {
      cursor = cursor.sort(sortCriteria)
    }

    const limit = params.limit || 100
    cursor = cursor.limit(limit)

    const documents = await cursor.toArray()

    logger.info(
      `[${requestId}] Query executed successfully, returned ${documents.length} documents`
    )

    return NextResponse.json({
      message: `Found ${documents.length} documents`,
      documents,
      documentCount: documents.length,
    })
  } catch (error) {
    const errorMessage = getErrorMessage(error, 'Unknown error occurred')
    logger.error(`[${requestId}] MongoDB query failed:`, error)

    return NextResponse.json({ error: `MongoDB query failed: ${errorMessage}` }, { status: 500 })
  } finally {
    if (client) {
      await client.close()
    }
  }
})
