<?php

namespace FleekDash\Controllers\Schema\FieldDetectors;

if (!\function_exists('fleekdash_log_debug')) {
    require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/debug-helpers.php';
}

/**
 * REST Field Detector
 *
 * Handles WordPress REST API registered meta fields.
 * Lower priority detector that captures fields registered through register_rest_field().
 *
 * @since 2.0.0 Extracted from monolithic SchemaController
 */
class RestFieldDetector
{
    private $priority = 7;

    /**
     * Check if REST API is available
     *
     * @return bool
     */
    public function isAvailable()
    {
        return function_exists('register_rest_field');
    }

    /**
     * Get detector priority
     *
     * @return int
     */
    public function getPriority()
    {
        return $this->priority;
    }

    /**
     * Get REST API registered fields for a post type
     *
     * @param string $post_type
     * @return array
     */
    public function getFields($post_type)
    {
        $fields = [];

        if (!$this->isAvailable()) {
            fleekdash_log_debug("FleekDash [RestFieldDetector]: REST API not available");
            return $fields;
        }

        try {
            fleekdash_log_debug("FleekDash [RestFieldDetector]: Detecting REST fields for post type: {$post_type}");

            // Get registered meta fields for this post type
            $registered_meta = get_registered_meta_keys('post', $post_type);

            foreach ($registered_meta as $meta_key => $meta_config) {
                // Skip private meta fields
                if (strpos($meta_key, '_') === 0) {
                    continue;
                }

                // Only include fields that are shown in REST
                if (empty($meta_config['show_in_rest'])) {
                    continue;
                }

                $field_config = [
                    'name' => $meta_key,
                    'label' => $this->formatLabel($meta_key),
                    'type' => $this->mapRestType($meta_config['type'] ?? 'string'),
                    'component' => $this->mapRestComponent($meta_config['type'] ?? 'string'),
                    'required' => false,
                    'validation' => [],
                    'description' => $meta_config['description'] ?? '',
                    'default' => $meta_config['default'] ?? null,
                    'meta_key' => $meta_key,
                    'source' => 'WordPress REST',
                    'source_priority' => $this->priority,
                    'rest_config' => $meta_config
                ];

                // Add validation based on meta config
                if (isset($meta_config['sanitize_callback']) && is_callable($meta_config['sanitize_callback'])) {
                    $field_config['validation']['sanitize'] = $meta_config['sanitize_callback'];
                }

                $fields[$meta_key] = $field_config;

                fleekdash_log_debug("FleekDash [RestFieldDetector]: Added REST field '{$meta_key}' " .
                    "(type: {$meta_config['type']})");
            }

            fleekdash_log_debug("FleekDash [RestFieldDetector]: Total REST fields processed: " . count($fields));

        } catch (\Exception $e) {
            fleekdash_log_error("FleekDash [RestFieldDetector]: Error processing REST fields: " . $e->getMessage());
        }

        return $fields;
    }

    /**
     * Map REST API type to our standardized type
     *
     * @param string $rest_type
     * @return string
     */
    private function mapRestType($rest_type)
    {
        $type_map = [
            'string' => 'text',
            'integer' => 'number',
            'number' => 'number',
            'boolean' => 'boolean',
            'array' => 'multiselect',
            'object' => 'textarea'
        ];

        return $type_map[$rest_type] ?? 'text';
    }

    /**
     * Map REST API type to component
     *
     * @param string $rest_type
     * @return string
     */
    private function mapRestComponent($rest_type)
    {
        $component_map = [
            'string' => 'input',
            'integer' => 'input',
            'number' => 'input',
            'boolean' => 'checkbox',
            'array' => 'multiselect',
            'object' => 'textarea'
        ];

        return $component_map[$rest_type] ?? 'input';
    }

    /**
     * Format field label from meta key
     *
     * @param string $key
     * @return string
     */
    private function formatLabel($key)
    {
        return ucwords(str_replace(['_', '-'], ' ', $key));
    }
}
