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

namespace Simplyin\Payment\Observer;

use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Simplyin\Payment\Model\OrderSyncRecorder;
use Psr\Log\LoggerInterface;

/**
 * Save SimplyIN order data observer
 *
 * Saves SimplyIN order ID and creates sync entry when order is placed
 */
class CreateSimplyinAccountOnOrder implements ObserverInterface
{
    /**
     * @var OrderRepositoryInterface
     */
    protected $orderRepository;

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

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

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

    /**
     * Execute observer
     *
     * Saves SimplyIN order ID to order table and creates sync entry
     *
     * @param Observer $observer
     * @return void
     */
    public function execute(Observer $observer): void
    {
        try {
            /** @var \Magento\Sales\Model\Order $order */
            $order = $observer->getEvent()->getOrder();

            if (!$order || !$order->getId()) {
                return;
            }

            // Check if this is a SimplyIN payment
            $payment = $order->getPayment();
            if (!$payment || $payment->getMethod() !== 'simplyin_payment') {
                return;
            }

            // Get SimplyIN order ID from payment additional information
            $simplyinOrderId = $payment->getAdditionalInformation('simplyin_order_id');

            if (!$simplyinOrderId) {
                $this->logger->info('SimplyIN Observer: No SimplyIN order ID found for order #' . $order->getIncrementId());
                return;
            }

            $this->logger->info('SimplyIN Observer: Processing order #' . $order->getIncrementId());

            // Store SimplyIN order ID only in simplyin_order_sync table (not in sales_order)
            $this->orderSyncRecorder->record((int)$order->getId(), 'synced', $simplyinOrderId);

            $this->logger->info('SimplyIN Observer: Synced order sync entry', [
                'magento_order_id' => $order->getId(),
                'simplyin_order_id' => $simplyinOrderId
            ]);
        } catch (\Exception $e) {
            $this->logger->error('SimplyIN Observer Error: ' . $e->getMessage(), [
                'trace' => $e->getTraceAsString()
            ]);
        }
    }
}
