/**
 * Queue Handler for async server provisioning
 * Processes messages from PROVISION_QUEUE
 */

import type { Env, ProvisionQueueMessage } from '../types';
import { ProvisioningService } from '../services/provisioning-service';

/**
 * Queue message handler
 * Called by Cloudflare Workers Queue consumer
 */
export async function handleProvisionQueue(
  batch: MessageBatch<ProvisionQueueMessage>,
  env: Env
): Promise<void> {
  const provisioningService = new ProvisioningService(
    env,
    env.DB,
    env.USER_DB,
    env.LINODE_API_KEY,
    env.VULTR_API_KEY
  );

  for (const message of batch.messages) {
    try {
      console.log(`[Queue] Processing message for order ${message.body.order_id}`);

      await provisioningService.processQueueMessage(message.body);

      // Acknowledge successful processing
      message.ack();
      console.log(`[Queue] Order ${message.body.order_id} processed successfully`);
    } catch (error) {
      console.error(`[Queue] Error processing order ${message.body.order_id}:`, error);

      // Retry the message (will go to DLQ after max_retries)
      message.retry();
    }
  }
}
