<?php
/**
 * Document Service
 *
 * Handles AI-driven document creation in WordPress.
 * Migrated from integrations/openai/tools/WordPress.php (createDocument only).
 *
 * @package FleekDash\AI\Services
 * @since 2.3.0
 */

namespace FleekDash\AI\Services;

defined('ABSPATH') || exit;

/**
 * Class DocumentService
 *
 * Creates WordPress posts/documents from AI-detected intent.
 */
class DocumentService
{
    /**
     * Create a document (WordPress post) for AI content generation.
     *
     * @param array{id?: string, title: string, kind?: string, post_type?: string} $args
     * @return array{success: bool, document_id?: string, post_id?: int, url?: string, edit_url?: string, error?: string}
     */
    public static function createDocument(array $args): array
    {
        $title = trim($args['title'] ?? '');
        $kind = \sanitize_text_field($args['kind'] ?? 'text');
        $post_type = \sanitize_text_field($args['post_type'] ?? '');

        if (empty($post_type)) {
            $post_type = \post_type_exists('fleekdash_document') ? 'fleekdash_document' : 'post';
        }

        if (!\post_type_exists($post_type)) {
            $post_type = \post_type_exists('fleekdash_document') ? 'fleekdash_document' : 'post';
        }

        if (empty($title)) {
            return [
                'success' => false,
                'error' => 'Title is required.',
            ];
        }

        $document_id = 'doc_' . \uniqid();

        $post_data = [
            'post_title' => $title,
            'post_content' => "# {$title}\n\n*Document being created...*",
            'post_status' => 'pending',
            'post_type' => $post_type,
            'meta_input' => [
                'document_kind' => $kind,
                'created_via_ai' => true,
                'created_at' => \current_time('mysql'),
                'document_id' => $document_id,
            ],
        ];

        $post_id = \wp_insert_post($post_data, true);

        if (\is_wp_error($post_id)) {
            return [
                'success' => false,
                'error' => 'Failed to create WordPress post',
            ];
        }

        \update_post_meta($post_id, 'document_id', $document_id);

        return [
            'success' => true,
            'id' => $document_id,
            'document_id' => $document_id,
            'post_id' => $post_id,
            'title' => $title,
            'kind' => $kind,
            'url' => \get_permalink($post_id),
            'edit_url' => \get_edit_post_link($post_id),
            'message' => "Document created successfully. Now I'll provide comprehensive content about '{$title}'.",
        ];
    }
}
