<?php
namespace AI_BotKit\Integration;

use WP_REST_Server;
use WP_REST_Request;
use WP_REST_Response;

class REST_API {
    private const API_NAMESPACE = 'ai-botkit/v1';

    public function __construct() {
        $this->init_hooks();
    }

    private function init_hooks(): void {
        add_action('rest_api_init', [$this, 'register_routes']);
    }

    public function register_routes(): void {
        register_rest_route(self::API_NAMESPACE, '/setToken', [
            'methods' => WP_REST_Server::CREATABLE,
            'callback' => [$this, 'handle_set_token'],
            'permission_callback' => '__return_true',
            'args' => [
                'token' => [
                    'required' => true,
                    'type' => 'string',
                    'sanitize_callback' => 'sanitize_text_field',
                ],
                'nonce' => [
                    'required' => true,
                    'type' => 'string',
                    'sanitize_callback' => 'sanitize_text_field',
                ],
            ],
        ]);

        register_rest_route(self::API_NAMESPACE, '/post-types', [
            'methods'             => WP_REST_Server::READABLE,
            'callback'            => [$this, 'get_post_types'],
            'permission_callback' => [$this, 'verify_token'],
        ]);

        register_rest_route(self::API_NAMESPACE, '/posts/(?P<post_type>[\w-]+)', [
            'methods'             => WP_REST_Server::READABLE,
            'callback'            => [$this, 'get_posts_by_type'],
            'permission_callback' => [$this, 'verify_token'],
        ]);

        register_rest_route(self::API_NAMESPACE, '/posts/(?P<id>\\d+)/content', [
            'methods'             => WP_REST_Server::READABLE,
            'callback'            => [$this, 'get_post_content'],
            'permission_callback' => [$this, 'verify_token'],
        ]);
    }

    public function verify_token(WP_REST_Request $request): bool {
        $auth_header = $request->get_header('Authorization');
        if (!$auth_header) {
            return false;
        }

        list($token) = sscanf($auth_header, 'Bearer %s');
        if (!$token) {
            return false;
        }

        $stored_token = get_option('ai_botkit_saas_connect_token');
        
        return $token === $stored_token;
    }

    public function get_post_types(WP_REST_Request $request): WP_REST_Response {
        $post_types = get_post_types(['public' => true], 'objects');
        $post_type_names = [];

        foreach ($post_types as $post_type) {
            $post_type_names[] = [
                'name'  => $post_type->name,
                'label' => $post_type->label,
            ];
        }

        return new WP_REST_Response($post_type_names, 200);
    }

    public function get_posts_by_type(WP_REST_Request $request): WP_REST_Response {
        $post_type = $request->get_param('post_type');
        $posts = get_posts([
            'post_type'   => $post_type,
            'numberposts' => -1,
            'post_status' => 'publish',
        ]);

        if (empty($posts)) {
            return new WP_REST_Response(['error' => 'No posts found for this post type'], 404);
        }

        $post_data = [];
        foreach ($posts as $post) {
            $post_data[] = [
                'id'    => $post->ID,
                'title' => $post->post_title,
                'excerpt' => $post->post_excerpt,
                'date' => $post->post_date,
            ];
        }

        return new WP_REST_Response($post_data, 200);
    }

    public function get_post_content(WP_REST_Request $request): WP_REST_Response {
        $post_id = $request->get_param('id');
        $post = get_post($post_id);

        if (!$post) {
            return new WP_REST_Response(['error' => 'Post not found'], 404);
        }

        $title = $post->post_title;
        $excerpt = $post->post_excerpt;

        $content = get_the_content(null, false, $post);
        $content_text = wp_strip_all_tags($content);

        // Allow plugins to enrich post content before sending to SaaS
        $content_text = apply_filters( 'ai_botkit_enrich_post_content', $content_text, $post_id, $post->post_type );

        return new WP_REST_Response(['content' => $content_text, 'title' => $title, 'excerpt' => $excerpt], 200);
    }

    public function handle_set_token(WP_REST_Request $request): WP_REST_Response {
        $token = $request->get_param('token');
        $nonce = $request->get_param('nonce');

        $original_nonce = get_transient('ai_botkit_onboarding_nonce');
        if ($original_nonce === false || $original_nonce !== $nonce) {
            return new WP_REST_Response(['error' => 'Invalid nonce'], 403);
        }

        delete_transient('ai_botkit_onboarding_nonce');

        update_option('ai_botkit_saas_connect_token', $token, false);

        return new WP_REST_Response(['success' => true], 200);
    }
}