<?php
/**
 * WordChat Plugin Test Suite
 *
 * PHPUnit tests for WordPress plugin functionality
 *
 * Requirements:
 * - WordPress Test Suite installed
 * - PHPUnit 9+
 * - WP-CLI
 *
 * Run tests:
 *   phpunit
 *   phpunit --filter test_plugin_activation
 *   phpunit --coverage-html coverage/
 */

class WordChat_Test extends WP_UnitTestCase {

    /**
     * Test plugin is Pro version
     */
    public function test_is_pro_plugin() {
        $this->assertTrue(defined('WORDCHAT_IS_PRO'));
        $this->assertTrue(WORDCHAT_IS_PRO);
        $this->assertEquals('wordchat-pro', WORDCHAT_PLUGIN_SLUG);
    }

    /**
     * Test plugin activation
     */
    public function test_plugin_activation() {
        // Activate plugin
        activate_plugin('wordchat-pro/wordchat-pro.php');

        // Check if plugin is active
        $this->assertTrue(is_plugin_active('wordchat-pro/wordchat-pro.php'));

        // Check if options are created
        $this->assertNotEmpty(get_option('wordchat_site_id'));
        $this->assertNotEmpty(get_option('wordchat_api_key'));
    }

    /**
     * Test site registration
     */
    public function test_site_registration() {
        // Mock API response
        add_filter('pre_http_request', function($preempt, $args, $url) {
            if (strpos($url, '/register') !== false) {
                return [
                    'response' => ['code' => 200],
                    'body' => json_encode([
                        'site_id' => 'test-site-id',
                        'api_key' => 'test-api-key',
                        'status' => 'created'
                    ])
                ];
            }
            return $preempt;
        }, 10, 3);

        // Trigger registration
        wordchat_register_plugin();

        // Check options set
        $this->assertEquals('test-site-id', get_option('wordchat_site_id'));
        $this->assertEquals('test-api-key', get_option('wordchat_api_key'));
    }

    /**
     * Test content sync on publish
     */
    public function test_content_sync() {
        // Set up credentials
        update_option('wordchat_site_id', 'test-site-id');
        update_option('wordchat_api_key', 'test-api-key');

        // Create a test post
        $post_id = $this->factory->post->create([
            'post_title' => 'Test Post',
            'post_content' => 'Test content',
            'post_status' => 'publish',
            'post_type' => 'post'
        ]);

        // Mark for sync
        update_post_meta($post_id, 'wordchat_synced', true);

        // Mock API response
        add_filter('pre_http_request', function($preempt, $args, $url) {
            if (strpos($url, '/ingest') !== false) {
                return [
                    'response' => ['code' => 200],
                    'body' => json_encode([
                        'status' => 'success',
                        'chunks_processed' => 1
                    ])
                ];
            }
            return $preempt;
        }, 10, 3);

        // Trigger sync
        $post = get_post($post_id);
        do_action('publish_post', $post_id, $post);

        // Check sync status
        $this->assertEquals('pending', get_post_meta($post_id, 'wordchat_sync_status', true));
    }

    /**
     * Test unsync functionality
     */
    public function test_content_unsync() {
        // Set up
        update_option('wordchat_site_id', 'test-site-id');
        update_option('wordchat_api_key', 'test-api-key');

        $post_id = $this->factory->post->create([
            'post_title' => 'Test Post',
            'post_status' => 'publish'
        ]);

        update_post_meta($post_id, 'wordchat_synced', true);

        // Mock API response
        add_filter('pre_http_request', function($preempt, $args, $url) {
            if (strpos($url, '/unsync') !== false) {
                return [
                    'response' => ['code' => 200],
                    'body' => json_encode(['status' => 'unsynced'])
                ];
            }
            return $preempt;
        }, 10, 3);

        // Trigger unsync (simulate admin action)
        // This would normally come from admin.php
        $response = wp_remote_post(WORDCHAT_API_URL . '/unsync', [
            'body' => json_encode([
                'site_id' => 'test-site-id',
                'api_key' => 'test-api-key',
                'url' => get_permalink($post_id)
            ]),
            'headers' => ['Content-Type' => 'application/json']
        ]);

        $this->assertEquals(200, wp_remote_retrieve_response_code($response));
    }

    /**
     * Test license activation
     */
    public function test_license_activation() {
        update_option('wordchat_site_id', 'test-site-id');

        // Mock successful activation
        add_filter('pre_http_request', function($preempt, $args, $url) {
            if (strpos($url, '/license/activate') !== false) {
                return [
                    'response' => ['code' => 200],
                    'body' => json_encode([
                        'success' => true,
                        'activation_token' => 'test-token',
                        'message' => 'License activated'
                    ])
                ];
            }
            return $preempt;
        }, 10, 3);

        // Simulate activation
        $response = wp_remote_post(WORDCHAT_API_URL . '/license/activate', [
            'body' => json_encode([
                'license_key' => 'WC-PRO-TEST-KEY',
                'site_id' => 'test-site-id',
                'domain' => get_site_url()
            ]),
            'headers' => ['Content-Type' => 'application/json']
        ]);

        $this->assertEquals(200, wp_remote_retrieve_response_code($response));
        $body = json_decode(wp_remote_retrieve_body($response), true);
        $this->assertTrue($body['success']);
    }

    /**
     * Test update check
     */
    public function test_update_check() {
        update_option('wordchat_license_key', 'WC-PRO-TEST-KEY');
        update_option('wordchat_site_id', 'test-site-id');

        // Mock update available
        add_filter('pre_http_request', function($preempt, $args, $url) {
            if (strpos($url, '/updates/check') !== false) {
                return [
                    'response' => ['code' => 200],
                    'body' => json_encode([
                        'authorized' => true,
                        'update_available' => true,
                        'latest_version' => '0.1.27',
                        'download_url' => 'https://test.com/plugin.zip'
                    ])
                ];
            }
            return $preempt;
        }, 10, 3);

        // Create updater instance
        if (class_exists('WordChat_Pro_Updater')) {
            $updater = new WordChat_Pro_Updater(
                __FILE__,
                '0.1.26',
                WORDCHAT_API_URL
            );

            // This would normally be called by WordPress
            // We're just testing the response handling
            $this->assertTrue(true); // Placeholder
        }
    }

    /**
     * Test free update check uses /updates/check
     */
    public function test_free_update_check_uses_updates_check() {
        update_option('wordchat_site_id', 'test-site-id');
        update_option('wordchat_api_key', 'test-api-key');

        $called = false;

        // Mock update available
        add_filter('pre_http_request', function($preempt, $args, $url) use (&$called) {
            if (strpos($url, '/updates/check') !== false) {
                $called = true;
                return [
                    'response' => ['code' => 200],
                    'body' => json_encode([
                        'authorized' => true,
                        'update_available' => true,
                        'latest_version' => '0.1.27',
                        'download_url' => 'https://test.com/plugin.zip',
                        'info_url' => 'https://www.word.chat',
                        'requires_wp_version' => '6.7',
                        'requires_php_version' => '7.4'
                    ])
                ];
            }
            return $preempt;
        }, 10, 3);

        $updater = new WordChat_Updater(__FILE__, '0.1.26');
        $transient = (object) array(
            'checked' => array('wordchat-pro/wordchat-pro.php' => '0.1.26'),
            'response' => array(),
            'no_update' => array()
        );

        $result = $updater->check_for_updates($transient);

        $this->assertTrue($called);
        $this->assertNotEmpty($result->response);
    }

    /**
     * Test API proxy
     */
    public function test_api_proxy() {
        update_option('wordchat_site_id', 'test-site-id');
        update_option('wordchat_api_key', 'test-api-key');

        // Mock chat query
        add_filter('pre_http_request', function($preempt, $args, $url) {
            if (strpos($url, '/query') !== false) {
                return [
                    'response' => ['code' => 200],
                    'body' => 'data: {"type":"sources","sources":[]}\n\n' .
                             'data: {"type":"token","content":"Test answer"}\n\n' .
                             'data: {"type":"done"}\n\n'
                ];
            }
            return $preempt;
        }, 10, 3);

        // Test API proxy endpoint
        // This would be called via AJAX from frontend
        $_POST['question'] = 'Test question';
        $_POST['nonce'] = wp_create_nonce('wordchat_query');

        // Simulate AJAX call
        // In real test, would call wordchat_proxy_query() function
        $this->assertTrue(true); // Placeholder
    }

    /**
     * Test plugin deactivation cleanup
     */
    public function test_plugin_deactivation() {
        // Schedule cron events
        wp_schedule_event(time(), 'daily', 'wordchat_cleanup_stuck_syncs');
        wp_schedule_event(time(), 'daily', 'wordchat_daily_telemetry');

        // Verify scheduled
        $this->assertNotFalse(wp_next_scheduled('wordchat_cleanup_stuck_syncs'));
        $this->assertNotFalse(wp_next_scheduled('wordchat_daily_telemetry'));

        // Deactivate
        wordchat_deactivation_cleanup();

        // Verify cleaned up
        $this->assertFalse(wp_next_scheduled('wordchat_cleanup_stuck_syncs'));
        $this->assertFalse(wp_next_scheduled('wordchat_daily_telemetry'));
    }

    /**
     * Test plugin uninstall cleanup
     */
    public function test_plugin_uninstall() {
        // Set up options
        update_option('wordchat_site_id', 'test');
        update_option('wordchat_api_key', 'test');
        update_option('wordchat_license_key', 'test');

        // Create test post with meta
        $post_id = $this->factory->post->create();
        update_post_meta($post_id, 'wordchat_synced', true);
        update_post_meta($post_id, 'wordchat_sync_status', 'success');

        // Simulate uninstall
        define('WP_UNINSTALL_PLUGIN', true);
        include dirname(dirname(__FILE__)) . '/uninstall.php';

        // Check cleanup
        $this->assertFalse(get_option('wordchat_site_id'));
        $this->assertFalse(get_option('wordchat_api_key'));
        $this->assertFalse(get_post_meta($post_id, 'wordchat_synced', true));
    }

    /**
     * Test admin page renders
     */
    public function test_admin_page_renders() {
        // Set current user as admin
        $admin_id = $this->factory->user->create(['role' => 'administrator']);
        wp_set_current_user($admin_id);

        // Check capability
        $this->assertTrue(current_user_can('manage_options'));

        // Render admin page
        ob_start();
        if (function_exists('wordchat_render_admin_page')) {
            wordchat_render_admin_page();
        }
        $output = ob_get_clean();

        // Check output contains key elements
        $this->assertStringContainsString('WordChat', $output);
    }

    /**
     * Test free plan limits
     */
    public function test_free_plan_post_limit() {
        update_option('wordchat_is_paid', '0');

        // Create 11 posts (over free limit of 10)
        for ($i = 1; $i <= 11; $i++) {
            $post_id = $this->factory->post->create([
                'post_title' => "Test Post $i",
                'post_status' => 'publish',
                'post_type' => 'post'
            ]);
            update_post_meta($post_id, 'wordchat_synced', true);
        }

        // Check that 11th post sync would fail
        // (This would be caught by backend API, not plugin)
        $this->assertTrue(true); // Placeholder
    }

    /**
     * Cleanup after each test
     */
    public function tearDown(): void {
        parent::tearDown();

        // Clean up options
        delete_option('wordchat_site_id');
        delete_option('wordchat_api_key');
        delete_option('wordchat_is_paid');
        delete_option('wordchat_license_key');

        // Remove filters
        remove_all_filters('pre_http_request');
    }
}
