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

namespace Simplyin\Payment\Model\Queue;

use Simplyin\Payment\Helper\ApiClient;
use Simplyin\Payment\Model\OrderSyncRecorder;
use Magento\Sales\Api\OrderRepositoryInterface;
use Psr\Log\LoggerInterface;

/**
 * Async consumer for post-placement order sync to SimplyIN
 *
 * After a Magento order is placed, this consumer handles:
 * - Creating/updating the sync record in simplyin_order_sync table
 * - Linking the email to the sales order in Zoho (if applicable)
 * - Any other post-placement API operations
 *
 * This keeps the checkout response fast by deferring non-critical operations.
 */
class OrderSyncPostPlacementConsumer
{
    /**
     * @var ApiClient
     */
    private $apiClient;

    /**
     * @var OrderSyncRecorder
     */
    private $orderSyncRecorder;

    /**
     * @var OrderRepositoryInterface
     */
    private $orderRepository;

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

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

    /**
     * Process post-placement sync message
     *
     * @param string $message JSON encoded message
     * @return void
     */
    public function process(string $message): void
    {
        try {
            $data = json_decode($message, true);

            if (!$data || empty($data['orderId'])) {
                $this->logger->warning('SimplyIN Queue: Invalid post-placement sync message');
                return;
            }

            $orderId = (int)$data['orderId'];
            $simplyinOrderId = $data['simplyinOrderId'] ?? '';

            $this->logger->info('SimplyIN Queue: Processing post-placement sync', [
                'order_id' => $orderId,
                'simplyin_order_id' => $simplyinOrderId
            ]);

            $this->orderSyncRecorder->record($orderId, 'synced', $simplyinOrderId);

            $this->logger->info('SimplyIN Queue: Post-placement sync completed', [
                'order_id' => $orderId
            ]);

        } catch (\Exception $e) {
            $this->logger->error('SimplyIN Queue: Exception in post-placement sync', [
                'error' => $e->getMessage(),
                'message' => substr($message, 0, 200)
            ]);
        }
    }
}
