<?php

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

/**
 * This file depends on WordPress core functionality.
 * The following constants and types are defined by WordPress and will be available at runtime:
 * - CONTENT_CRAFT_AI_PLUGIN_PATH: Plugin path constant defined in the main plugin file
 * - WP_REST_Response: WordPress REST API response class
 */

// Include our new controller
require_once CONTENT_CRAFT_AI_PLUGIN_PATH . 'app/controllers/article-generator/ArticleGenerationController.php';
require_once CONTENT_CRAFT_AI_PLUGIN_PATH . 'app/controllers/article-generator/PostCreationManager.php';

// Include necessary files
require_once __DIR__ . '/single-article.php'; // Include single-article.php for the API function

/**
 * Handle bulk article generation request
 * 
 * @param WP_REST_Request $request The request object
 * @return WP_REST_Response The response object
 */
function content_craft_ai_handle_bulk_article_generation($request)
{
    try {
        $params = $request->get_json_params();

        // Get the controller instance
        $controller = ContentCraftAI_ArticleGenerationController::get_instance();

        // Use the controller to generate bulk articles
        $result = $controller->generate_bulk_articles($params);

        // Check if the result contains validation errors
        if (!$result['success'] && isset($result['failedArticles'])) {
            // Make sure to include the results array in the response if it exists
            return new WP_REST_Response([
                'success' => false,
                'message' => $result['message'] ?? 'Some articles failed validation',
                'failedArticles' => $result['failedArticles'] ?? [],
                'results' => $result['results'] ?? [],
                'data' => [
                    'failedArticles' => $result['failedArticles'] ?? []
                ],
                'code' => $result['code'] ?? 403
            ], $result['code'] ?? 403);
        }

        // Return the result as is for success or other error cases
        return new WP_REST_Response($result, $result['code'] ?? ($result['success'] ? 200 : 500));
    } catch (Exception $e) {
        return new WP_REST_Response([
            'success' => false,
            'message' => $e->getMessage()
        ], 500);
    }
}
