<?php

namespace PortalPeople\magento\jobs;

use Yii;
use yii\base\BaseObject;
use common\components\queue\JobInterface;
use PortalPeople\magento\services\OrderImportService;
use PortalPeople\magento\services\MonitoringService;
use PortalPeople\magento\services\OrderSnapshotService;

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


    public function execute($queue): void
    {
        $orderImportService = new OrderImportService();
        $module = $orderImportService->getConfiguredModule();
        if ($module === null) {
            Yii::warning('Magento import job skipped: module not configured.', 'magento');
            return;
        }

        $snapshotService = new OrderSnapshotService();
        $orders = $snapshotService->loadNewOrdersSnapshot($module, false);
        $items = $orders['items'] ?? [];
        \yii\helpers\Console::output("Loaded " . count($items) . " new orders.");
        if ($this->limit > 0) {
        $items = array_slice($items, 0, $this->limit);
        }
            
        \yii\helpers\Console::output("Processing new orders.");
        $summary = $orderImportService->importOrders($items);
        (new MonitoringService())->recordImportRun($summary);
        \yii\helpers\Console::output("Magento order import job completed. Imported: {$summary['imported']}, Failed: {$summary['failed']}, Limit: {$this->limit}");
        Yii::$app->queue->jobname('magento-import-orders')->delay(300)->push(new self(['limit' => $this->limit]));
    }
}
