/**
 * Queue Jobs API
 *
 * Endpunkt zum Abrufen der Jobs einer Queue.
 * Nur für Super-Admins zugänglich.
 */

import { getPayload } from 'payload'
import config from '@payload-config'
import { NextRequest, NextResponse } from 'next/server'
import { getQueue, QUEUE_NAMES } from '@/lib/queue'
import { createSafeLogger } from '@/lib/security'

const logger = createSafeLogger('API:AdminQueueJobs')

interface UserWithAdmin {
  id: number
  isSuperAdmin?: boolean
}

type JobState = 'waiting' | 'active' | 'completed' | 'failed' | 'delayed'

/**
 * GET /api/admin/queues/[queueName]/jobs
 *
 * Gibt die Jobs einer Queue zurück.
 * Query-Parameter:
 * - status: waiting | active | completed | failed | delayed (default: waiting)
 * - start: number (default: 0)
 * - end: number (default: 20)
 */
export async function GET(
  req: NextRequest,
  { params }: { params: Promise<{ queueName: string }> },
) {
  try {
    const payload = await getPayload({ config })

    // Authentifizierung prüfen
    const { user } = await payload.auth({ headers: req.headers })

    if (!user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const typedUser = user as UserWithAdmin

    // Nur Super-Admins haben Zugriff
    if (!typedUser.isSuperAdmin) {
      return NextResponse.json(
        { error: 'Forbidden - Super admin access required' },
        { status: 403 },
      )
    }

    const { queueName } = await params

    // Queue-Namen validieren
    const validQueues = Object.values(QUEUE_NAMES)
    if (!validQueues.includes(queueName as typeof validQueues[number])) {
      return NextResponse.json(
        { error: `Invalid queue name. Valid: ${validQueues.join(', ')}` },
        { status: 400 },
      )
    }

    // Query-Parameter
    const { searchParams } = new URL(req.url)
    const status = (searchParams.get('status') || 'waiting') as JobState
    const start = parseInt(searchParams.get('start') || '0', 10)
    const end = parseInt(searchParams.get('end') || '20', 10)

    const validStatuses: JobState[] = ['waiting', 'active', 'completed', 'failed', 'delayed']
    if (!validStatuses.includes(status)) {
      return NextResponse.json(
        { error: `Invalid status. Valid: ${validStatuses.join(', ')}` },
        { status: 400 },
      )
    }

    const queue = getQueue(queueName as typeof validQueues[number])

    // Jobs abrufen basierend auf Status
    let jobs
    switch (status) {
      case 'waiting':
        jobs = await queue.getWaiting(start, end)
        break
      case 'active':
        jobs = await queue.getActive(start, end)
        break
      case 'completed':
        jobs = await queue.getCompleted(start, end)
        break
      case 'failed':
        jobs = await queue.getFailed(start, end)
        break
      case 'delayed':
        jobs = await queue.getDelayed(start, end)
        break
    }

    // Jobs für Response formatieren
    const formattedJobs = jobs.map((job) => ({
      id: job.id,
      name: job.name,
      data: job.data,
      timestamp: job.timestamp,
      processedOn: job.processedOn,
      finishedOn: job.finishedOn,
      attemptsMade: job.attemptsMade,
      failedReason: job.failedReason,
      returnvalue: job.returnvalue,
      progress: job.progress,
    }))

    return NextResponse.json({
      queue: queueName,
      status,
      pagination: { start, end },
      count: formattedJobs.length,
      jobs: formattedJobs,
    })
  } catch (error) {
    logger.error('admin-queue-jobs error', error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Unknown error' },
      { status: 500 },
    )
  }
}
