<?php
/**
 * Copyright © Simplyin. All rights reserved.
 */
declare(strict_types=1);

namespace Simplyin\Payment\Model\Queue;

use Simplyin\Payment\Helper\ApiClient;
use Psr\Log\LoggerInterface;

/**
 * Async consumer for SimplyIN order status updates
 *
 * Processes order status update API calls asynchronously
 * so they don't block the checkout flow.
 */
class OrderStatusUpdateConsumer
{
    /**
     * @var ApiClient
     */
    private $apiClient;

    /**
     * @var LoggerInterface
     */
    private $logger;

    /**
     * @param ApiClient $apiClient
     * @param LoggerInterface $logger
     */
    public function __construct(
        ApiClient $apiClient,
        LoggerInterface $logger
    ) {
        $this->apiClient = $apiClient;
        $this->logger = $logger;
    }

    /**
     * Process order status update message
     *
     * @param string $message JSON encoded message with simplyinOrderId, magentoOrderId, authToken
     * @return void
     */
    public function process(string $message): void
    {
        try {
            $data = json_decode($message, true);

            if (!$data || empty($data['simplyinOrderId']) || empty($data['authToken'])) {
                $this->logger->warning('SimplyIN Queue: Invalid order status update message', [
                    'message' => substr($message, 0, 200)
                ]);
                return;
            }

            $simplyinOrderId = $data['simplyinOrderId'];
            $magentoOrderId = $data['magentoOrderId'] ?? '';
            $authToken = $data['authToken'];
            $status = $data['status'] ?? 'CONFIRMED';

            $this->logger->info('SimplyIN Queue: Processing order status update', [
                'simplyin_order_id' => $simplyinOrderId,
                'magento_order_id' => $magentoOrderId,
                'status' => $status
            ]);

            $response = $this->apiClient->updateOrderStatus($simplyinOrderId, $status, $authToken);

            if ($response['success']) {
                $this->logger->info('SimplyIN Queue: Order status updated successfully', [
                    'simplyin_order_id' => $simplyinOrderId,
                    'magento_order_id' => $magentoOrderId
                ]);
            } else {
                $this->logger->warning('SimplyIN Queue: Failed to update order status', [
                    'simplyin_order_id' => $simplyinOrderId,
                    'error' => $response['error'] ?? 'Unknown error'
                ]);
            }
        } catch (\Exception $e) {
            $this->logger->error('SimplyIN Queue: Exception processing order status update', [
                'error' => $e->getMessage(),
                'message' => substr($message, 0, 200)
            ]);
        }
    }
}
