/**
 * Individual Queue Item API Endpoints
 * 
 * Provides HTTP interface for individual queue item operations:
 * - GET /api/queue/[id] - Get specific queue item details
 * - DELETE /api/queue/[id] - Remove 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';

/**
 * GET /api/queue/[id] - Get queue item by ID
 * 
 * Returns full queue item details including progress events and results.
 * Returns 404 if item not found, 400 for invalid ID format.
 */
export const GET: 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');
    }
    
    // Get queue item
    const queueItem = queueManager.get(id);
    
    if (!queueItem) {
      throw new NotFoundError('Queue item not found');
    }
    
    // Return full item details
    return json(queueItem);
    
  } catch (error) {
    return handleApiError(error);
  }
};

/**
 * DELETE /api/queue/[id] - Remove queue item
 * 
 * Removes an item from the queue.
 * Returns 404 if item not found, 400 for invalid ID format,
 * 409 if item is currently being processed.
 */
export const DELETE: 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
    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');
    }
    
    // Prevent deletion of in-progress items
    if (existingItem.status === 'in_progress') {
      throw new ConflictError(
        'Cannot delete item that is currently being processed'
      );
    }
    
    // Remove the item
    const success = queueManager.remove(id);
    
    return json({
      success,
      message: 'Queue item removed successfully'
    });
    
  } catch (error) {
    return handleApiError(error);
  }
};