<?php

declare(strict_types=1);

namespace CloudXM\NFe\Admin\Controllers;

use CloudXM\NFe\Services\OrderInvoiceLifecycleService;
use CloudXM\SDK\Support\HasLogger;

/**
 * NFe Status Poll Controller
 *
 * Handles AJAX requests for polling NFe operation status
 */
class NFeStatusPollController
{
    use HasLogger;

    public function __construct(
        private OrderInvoiceLifecycleService $lifecycleService
    ) {
        add_action('wp_ajax_cloudxm_nfe_poll_status', [$this, 'handlePoll']);
    }

    /**
     * Handle status poll request
     */
    public function handlePoll(): void
    {
        try {
            check_ajax_referer('cloudxm_nfe_poll_status', 'nonce');
            if (!current_user_can('manage_woocommerce')) {
                wp_send_json_error(['message' => __('Insufficient permissions.', 'woocommerce-cloudxm-nfe')]);
                return;
            }

            $orderId = isset($_POST['order_id']) ? (int) $_POST['order_id'] : 0;
            if ($orderId === 0) {
                wp_send_json_error(['message' => __('Invalid order ID.', 'woocommerce-cloudxm-nfe')]);
                return;
            }

            $status = $this->lifecycleService->buildMetaBoxData(wc_get_order($orderId));

            wp_send_json_success([
                'status' => $status['status'],
                'is_processing' => in_array($status['status'], ['pending', 'processing']),
                'is_completed' => in_array($status['status'], ['issued', 'cancelled']),
            ]);
        } catch (\Throwable $e) {
            $this->log()->error('nfe.ajax-poll-status.exception', [
                'order_id' => $_POST['order_id'] ?? null,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);
            wp_send_json_error(['message' => __('Failed to poll status.', 'woocommerce-cloudxm-nfe')]);
        }
    }
}
