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

import { requireSuperAdmin, withAuth } from '@/lib/api/helpers';
import { errorResponse, ValidationError } from '@/lib/errors';
import { getQueueJobs } from '@/lib/services/system-monitoring.service';
import { QUEUE_CONFIGS, type QueueName } from '@/lib/queue';

export const GET = withAuth(async (req: NextRequest, ctx, params) => {
  try {
    requireSuperAdmin(ctx, 'admin.queues.jobs.list');

    const { queueName } = params;
    const validQueues = Object.keys(QUEUE_CONFIGS) as QueueName[];
    if (!validQueues.includes(queueName as QueueName)) {
      throw new ValidationError('Invalid queue name');
    }

    const url = new URL(req.url);
    const status = (url.searchParams.get('status') ?? 'failed') as
      | 'waiting'
      | 'active'
      | 'completed'
      | 'failed'
      | 'delayed';
    const page = Math.max(1, parseInt(url.searchParams.get('page') ?? '1', 10));
    const limit = Math.min(100, Math.max(1, parseInt(url.searchParams.get('limit') ?? '20', 10)));

    const result = await getQueueJobs(queueName as QueueName, status, page, limit);
    return NextResponse.json({ data: result });
  } catch (error) {
    return errorResponse(error);
  }
});
