import { createLogger } from '@sim/logger'
import { type NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { checkInternalAuth } from '@/lib/auth/hybrid'
import { generateId } from '@/lib/core/utils/uuid'
import { createMongoDBConnection, sanitizeCollectionName, validatePipeline } from '../utils'

const logger = createLogger('MongoDBExecuteAPI')

const ExecuteSchema = z.object({
  host: z.string().min(1, 'Host is required'),
  port: z.coerce.number().int().positive('Port must be a positive integer'),
  database: z.string().min(1, 'Database name is required'),
  username: z.string().min(1, 'Username is required'),
  password: z.string().min(1, 'Password is required'),
  authSource: z.string().optional(),
  ssl: z.enum(['disabled', 'required', 'preferred']).default('preferred'),
  collection: z.string().min(1, 'Collection name is required'),
  pipeline: z
    .union([z.string(), z.array(z.object({}).passthrough())])
    .transform((val) => {
      if (Array.isArray(val)) {
        return JSON.stringify(val)
      }
      return val
    })
    .refine((val) => val && val.trim() !== '', {
      message: 'Pipeline is required',
    }),
})

export async function POST(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 execute attempt`)
    return NextResponse.json({ error: auth.error || 'Unauthorized' }, { status: 401 })
  }

  try {
    const body = await request.json()
    const params = ExecuteSchema.parse(body)

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

    const sanitizedCollection = sanitizeCollectionName(params.collection)

    const pipelineValidation = validatePipeline(params.pipeline)
    if (!pipelineValidation.isValid) {
      logger.warn(`[${requestId}] Pipeline validation failed: ${pipelineValidation.error}`)
      return NextResponse.json(
        { error: `Pipeline validation failed: ${pipelineValidation.error}` },
        { status: 400 }
      )
    }

    const pipelineDoc = JSON.parse(params.pipeline)

    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)

    const cursor = coll.aggregate(pipelineDoc)
    const documents = await cursor.toArray()

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

    return NextResponse.json({
      message: `Aggregation completed, returned ${documents.length} documents`,
      documents,
      documentCount: documents.length,
    })
  } catch (error) {
    if (error instanceof z.ZodError) {
      logger.warn(`[${requestId}] Invalid request data`, { errors: error.errors })
      return NextResponse.json(
        { error: 'Invalid request data', details: error.errors },
        { status: 400 }
      )
    }

    const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'
    logger.error(`[${requestId}] MongoDB aggregation failed:`, error)

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