<?php

namespace RecastPaywall\CLI;

use WP_CLI;
use RecastPaywall\Sync\InventorySync;
use RecastPaywall\Services\EntitlementService;
use RecastPaywall\Api\RecastClient;

/**
 * WP-CLI commands for Recast Paywall
 */
class Commands {
    /**
     * Sync a specific post with Recast
     *
     * ## OPTIONS
     *
     * <post_id>
     * : The ID of the post to sync
     *
     * ## EXAMPLES
     *
     *     wp recast sync --post_id=123
     *
     * @param array $args
     * @param array $assoc_args
     */
    public function sync($args, $assoc_args) {
        $postId = intval($assoc_args['post_id'] ?? 0);
        
        if (!$postId) {
            WP_CLI::error('Please provide a valid post ID using --post_id');
        }

        $post = get_post($postId);
        
        if (!$post) {
            WP_CLI::error("Post with ID {$postId} not found");
        }

        WP_CLI::log("Syncing post: {$post->post_title} (ID: {$postId})");

        $inventorySync = new InventorySync(new RecastClient());
        $inventorySync->syncPost($postId, $post);

        $status = $inventorySync->getSyncStatus($postId);
        
        if (!empty($status['item_id'])) {
            WP_CLI::success("Post synced successfully. Recast Product ID: {$status['item_id']}");
        } else {
            WP_CLI::warning("Post sync may have failed. Check logs for details.");
        }
    }

    /**
     * Sync all published posts with Recast
     *
     * ## EXAMPLES
     *
     *     wp recast sync-all
     *
     * @param array $args
     * @param array $assoc_args
     */
    public function syncAll($args, $assoc_args) {
        // Use WP_Query for better performance and avoid meta_query for slow queries
        $query = new \WP_Query([
            'post_type' => 'post',
            'post_status' => 'publish',
            'posts_per_page' => -1,
            'fields' => 'ids',
            'no_found_rows' => true,
            'update_post_meta_cache' => false,
            'update_post_term_cache' => false,
        ]);
        
        // Filter posts that have paywall enabled using direct meta checks
        $post_ids = [];
        foreach ($query->posts as $post_id) {
            if (get_post_meta($post_id, '_recast_paywall_enabled', true)) {
                $post_ids[] = $post_id;
            }
        }
        
        // Get the actual post objects for the filtered IDs
        $posts = [];
        foreach ($post_ids as $post_id) {
            $post = get_post($post_id);
            if ($post) {
                $posts[] = $post;
            }
        }

        if (empty($posts)) {
            WP_CLI::warning('No paywalled posts found to sync');
            return;
        }

        WP_CLI::log("Found " . count($posts) . " posts to sync");

        $inventorySync = new InventorySync(new RecastClient());
        $progress = \WP_CLI\Utils\make_progress_bar('Syncing posts', count($posts));

        $successCount = 0;
        $errorCount = 0;

        foreach ($posts as $post) {
            try {
                $inventorySync->syncPost($post->ID, $post);
                $status = $inventorySync->getSyncStatus($post->ID);
                
                if (!empty($status['item_id'])) {
                    $successCount++;
                } else {
                    $errorCount++;
                }
            } catch (Exception $e) {
                $errorCount++;
                WP_CLI::debug("Error syncing post {$post->ID}: " . $e->getMessage());
            }

            $progress->tick();
        }

        $progress->finish();

        WP_CLI::success("Sync completed. Success: {$successCount}, Errors: {$errorCount}");
    }

    /**
     * Clear entitlement cache
     *
     * ## OPTIONS
     *
     * [--post_id=<post_id>]
     * : Clear cache for a specific post
     *
     * [--user_id=<user_id>]
     * : Clear cache for a specific user
     *
     * ## EXAMPLES
     *
     *     wp recast clear-cache
     *     wp recast clear-cache --post_id=123
     *     wp recast clear-cache --post_id=123 --user_id=456
     *
     * @param array $args
     * @param array $assoc_args
     */
    public function clearCache($args, $assoc_args) {
        $postId = intval($assoc_args['post_id'] ?? 0);
        $userId = intval($assoc_args['user_id'] ?? 0);

        $entitlementService = new EntitlementService(new RecastClient());

        if ($postId && $userId) {
            $entitlementService->clearCache($postId, $userId);
            WP_CLI::success("Cache cleared for post {$postId} and user {$userId}");
        } elseif ($postId) {
            $entitlementService->clearCache($postId);
            WP_CLI::success("Cache cleared for post {$postId}");
        } else {
            $entitlementService->clearCache();
            WP_CLI::success("All entitlement cache cleared");
        }
    }

    /**
     * Test Recast API connection
     *
     * ## EXAMPLES
     *
     *     wp recast test-connection
     *
     * @param array $args
     * @param array $assoc_args
     */
    public function testConnection($args, $assoc_args) {
        WP_CLI::log("Testing Recast API connection...");

        $client = new RecastClient();
        $result = $client->testConnection();

        if (is_wp_error($result)) {
            WP_CLI::error("Connection failed: " . $result->get_error_message());
        } else {
            WP_CLI::success("Connection successful!");
        }
    }

    /**
     * Get sync status for a post
     *
     * ## OPTIONS
     *
     * <post_id>
     * : The ID of the post to check
     *
     * ## EXAMPLES
     *
     *     wp recast status --post_id=123
     *
     * @param array $args
     * @param array $assoc_args
     */
    public function status($args, $assoc_args) {
        $postId = intval($assoc_args['post_id'] ?? 0);
        
        if (!$postId) {
            WP_CLI::error('Please provide a valid post ID using --post_id');
        }

        $post = get_post($postId);
        
        if (!$post) {
            WP_CLI::error("Post with ID {$postId} not found");
        }

        $inventorySync = new InventorySync(new RecastClient());
        $status = $inventorySync->getSyncStatus($postId);

        WP_CLI::log("Post: {$post->post_title} (ID: {$postId})");
        WP_CLI::log("Status: {$status['status']}");
        WP_CLI::log("Paywalled: " . ($status['is_paywalled'] ? 'Yes' : 'No'));
        
        if (!empty($status['item_id'])) {
            WP_CLI::log("Recast Product ID: {$status['item_id']}");
        }
        
        if (!empty($status['last_synced'])) {
            WP_CLI::log("Last Synced: {$status['last_synced']}");
        }
        
        if ($status['retry_count'] > 0) {
            WP_CLI::log("Retry Count: {$status['retry_count']}");
        }
    }
}
