<?php

namespace PortalPeople\virtualstock\jobs;

use Yii;
use yii\base\BaseObject;
use yii\queue\JobInterface;
use PortalPeople\virtualstock\exceptions\ApiException;
use PortalPeople\virtualstock\exceptions\RateLimitException;
use PortalPeople\virtualstock\Module;

/**
 * Queue job that runs a VirtualStock order import batch.
 *
 * Push via:
 *   Yii::$app->get($module->queueComponent)->push(new ImportOrderBatchJob([
 *       'limit'   => 100,
 *       'cursor'  => null,
 *       'dryRun'  => false,
 *   ]));
 */
class ImportOrderBatchJob extends BaseObject implements JobInterface
{
    /** Maximum orders to fetch in this batch (0 = use module default). */
    public int $limit = 0;

    /** ISO-8601 cursor override; null = use stored cursor. */
    public ?string $cursor = null;

    /** When true, preview only — no data is written. */
    public bool $dryRun = false;

    /**
     * @inheritdoc
     */
    public function execute($queue): void
    {
        /** @var Module|null $module */
        $module = Yii::$app->getModule('virtualstock');

        if ($module === null || !$module->isConfigured()) {
            Yii::warning('ImportOrderBatchJob: module not configured — skipping.', 'virtualstock');
            return;
        }

        $service = $module->createOrderImportService();

        try {
            $summary = $service->run($this->cursor, $this->limit, $this->dryRun);
        } catch (RateLimitException $e) {
            Yii::warning(
                'ImportOrderBatchJob: rate limit hit — will retry. ' . $e->getMessage(),
                'virtualstock'
            );
            throw $e;
        } catch (ApiException $e) {
            Yii::warning(
                'ImportOrderBatchJob: API error — will retry. ' . $e->getMessage(),
                'virtualstock'
            );
            throw $e;
        } catch (\Throwable $e) {
            Yii::error(
                'ImportOrderBatchJob: unexpected error — ' . $e->getMessage(),
                'virtualstock'
            );
            throw $e;
        }

        Yii::info(sprintf(
            'ImportOrderBatchJob complete: fetched=%d created=%d updated=%d failed=%d dryRun=%s',
            $summary['fetched'],
            $summary['created'],
            $summary['updated'],
            $summary['failed'],
            $this->dryRun ? 'yes' : 'no'
        ), 'virtualstock');

        if (!empty($summary['errors'])) {
            foreach ($summary['errors'] as $err) {
                Yii::error('ImportOrderBatchJob order error: ' . $err['message'], 'virtualstock');
            }
        }
    }
}
