<?php

/**
 * Content Craft AI - Cancel Generation API Handler
 */

if (!defined('ABSPATH')) {
  exit;
}

/**
 * Handle request to cancel an article generation
 * 
 * @param WP_REST_Request $request The REST API request.
 * @return WP_REST_Response The REST API response.
 */
function content_craft_ai_cancel_generation($request)
{
  // Get queue ID from the request
  $queue_id = $request->get_param('queueId');

  if (empty($queue_id)) {
    return new WP_REST_Response([
      'success' => false,
      'message' => 'Queue ID is required'
    ], 400);
  }

  // Get article status controller
  $article_status_controller = new ContentCraftAI_ArticleStatusController();

  // Get the generation to check if it's scheduled or has an API queue ID
  $generation = $article_status_controller->get_generation_by_queue_id($queue_id);

  if (!$generation) {
    return new WP_REST_Response([
      'success' => false,
      'message' => 'Generation not found'
    ], 404);
  }

  // For scheduled articles or articles without API queue ID, just update the database
  $parameters = !empty($generation['parameters']) ? $generation['parameters'] : [];
  $api_queue_id = isset($parameters['apiQueueId']) ? $parameters['apiQueueId'] : null;

  if ($generation['status'] === 'scheduled' || empty($api_queue_id)) {
    // Just update the status in the database
    $result = $article_status_controller->update_generation_status($queue_id, 'cancelled');

    if ($result) {
      return new WP_REST_Response([
        'success' => true,
        'message' => 'Generation cancelled successfully',
        'data' => [
          'queue_id' => $queue_id,
          'status' => 'cancelled'
        ]
      ], 200);
    } else {
      return new WP_REST_Response([
        'success' => false,
        'message' => 'Failed to cancel generation'
      ], 500);
    }
  }

  // For articles with API queue ID, call the external API to cancel
  // Get API key from options
  $api_key = get_option('content_craft_ai_api_key');

  if (empty($api_key)) {
    return new WP_REST_Response([
      'success' => false,
      'message' => 'API key not found. Please check your authentication.'
    ], 401);
  }

  // Prepare API request
  $api_url = defined('CONTENT_CRAFT_AI_EXTERNAL_API') ? CONTENT_CRAFT_AI_EXTERNAL_API : '';

  if (empty($api_url)) {
    return new WP_REST_Response([
      'success' => false,
      'message' => 'External API URL not defined'
    ], 500);
  }

  // Set up headers following the pattern from image-services.php
  $headers = [
    'Content-Type' => 'application/json',
    'x-api-key' => $api_key,
    'x-wp-domain' => wp_parse_url(get_site_url(), PHP_URL_HOST)
  ];

  // Set up request arguments
  $request_args = [
    'headers' => $headers,
    'method' => 'DELETE',
    'timeout' => 120
  ];

  // Make the API request to cancel the generation
  $response = wp_remote_request(
    $api_url . '/articles/queue/' . $api_queue_id,
    $request_args
  );

  // Handle API response
  if (is_wp_error($response)) {
    return new WP_REST_Response([
      'success' => false,
      'message' => 'Failed to cancel generation: ' . $response->get_error_message()
    ], 500);
  }

  $status_code = wp_remote_retrieve_response_code($response);
  $body = wp_remote_retrieve_body($response);
  $data = json_decode($body, true);

  // Update the status in our database regardless of API response
  $article_status_controller->update_generation_status($queue_id, 'cancelled');

  // Return success if API call was successful
  if ($status_code >= 200 && $status_code < 300 && !empty($data['success'])) {
    return new WP_REST_Response([
      'success' => true,
      'message' => 'Generation cancelled successfully',
      'data' => $data
    ], 200);
  } else {
    // If API call failed but we updated the database, still return partial success
    return new WP_REST_Response([
      'success' => true,
      'message' => 'Generation marked as cancelled but external API call failed',
      'api_response' => [
        'status' => $status_code,
        'data' => $data
      ]
    ], 200);
  }
}
