<?php

namespace PortalPeople\magento\jobs;

use Yii;
use yii\base\BaseObject;
use common\components\queue\JobInterface;
use PortalPeople\magento\Module;
use PortalPeople\magento\services\MagentoClient;

class ImportMagentoOrderJob extends BaseObject implements JobInterface
{
    public int $limit = 50;

    public function execute($queue): void
    {
        $module = Yii::$app->getModule('magento');
        if (!$module instanceof Module || !$module->isConfigured()) {
            Yii::warning('Magento import job skipped: module not configured.', 'magento');
            return;
        }

        $client = new MagentoClient($module->apiUrl, $module->accessToken);
        $orders = $client->getOrders(['searchCriteria[pageSize]' => $this->limit]);
        $items = $orders['items'] ?? [];

        foreach ($items as $item) {
            try {
                \PortalPeople\magento\models\Cart::newMagentoOrder($item);
            } catch (\Throwable $e) {
                $orderId = (string) ($item['entity_id'] ?? 'unknown');
                Yii::error('Magento import job failed for order ' . $orderId . ': ' . $e->getMessage(), 'magento');
            }
        }

        Yii::$app->queue
            ->delay(300)
            ->jobname('Magento import batch')
            ->push(new self(['limit' => $this->limit]));
    }
}
