/**
 * Queue Item Retry API Endpoint
 * 
 * Provides HTTP interface for retrying failed queue items:
 * - POST /api/queue/[id]/retry - Retry failed/unhealthy queue item
 */

import { json } from '@sveltejs/kit';
import { queueManager } from '$lib/server/queue/QueueManager';
import { handleApiError } from '$lib/server/api/errorHandler';
import { ValidationError, NotFoundError, ConflictError } from '$lib/server/api/errors';
import type { RequestHandler } from './$types';

/**
 * POST /api/queue/[id]/retry - Retry queue item
 * 
 * Resets a failed or unhealthy queue item to pending status for reprocessing.
 * Only items with status 'error' or 'unhealthy' can be retried.
 * 
 * Returns the updated queue item on success.
 * Returns 404 if item not found, 400 for invalid operations, 409 for wrong status.
 */
export const POST: RequestHandler = async ({ params }) => {
  try {
    const { id } = params;
    
    // Validate ID parameter
    if (!id || typeof id !== 'string') {
      throw new ValidationError('Queue item ID is required');
    }
    
    // Validate UUID format (basic check)
    const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
    if (!uuidPattern.test(id)) {
      throw new ValidationError('Invalid queue item ID format');
    }
    
    // Check if item exists
    const existingItem = queueManager.get(id);
    if (!existingItem) {
      throw new NotFoundError('Queue item not found');
    }
    
    // Check if item can be retried
    if (existingItem.status !== 'error' && existingItem.status !== 'unhealthy') {
      throw new ConflictError(
        `Cannot retry item with status '${existingItem.status}'. Only 'error' and 'unhealthy' items can be retried.`
      );
    }
    
    // Retry the item
    const retryResult = queueManager.retry(id);
    
    if (!retryResult) {
      // This shouldn't happen given our checks above, but handle it gracefully
      throw new Error('Failed to retry queue item');
    }
    
    // Return the updated item
    const updatedItem = queueManager.get(id);
    return json({
      success: true,
      item: updatedItem,
      message: 'Queue item has been reset and will be reprocessed'
    });
    
  } catch (error) {
    return handleApiError(error);
  }
};