<?php

namespace PortalPeople\virtualstock\commands;

use Yii;
use yii\console\Controller;
use yii\console\ExitCode;
use yii\helpers\Json;
use PortalPeople\virtualstock\jobs\ImportOrderBatchJob;
use PortalPeople\virtualstock\Module;

class OrderImportController extends Controller
{
    public ?string $cursor = null;
    public int $limit = 100;
    public bool $dryRun = false;

    public function options($actionID): array
    {
        return array_merge(parent::options($actionID), ['cursor', 'limit', 'dryRun']);
    }

    public function optionAliases(): array
    {
        return [
            'c' => 'cursor',
            'l' => 'limit',
            'd' => 'dryRun',
        ];
    }

    public function actionRun(): int
    {
        $module = Yii::$app->getModule('virtualstock');
        if (!$module instanceof Module) {
            $this->stderr("VirtualStock module is not registered.\n");
            return ExitCode::UNSPECIFIED_ERROR;
        }

        if (!$module->isConfigured()) {
            $this->stderr("VirtualStock module is not configured. Set apiEndpoint in module configuration.\n");
            return ExitCode::UNSPECIFIED_ERROR;
        }

        try {
            // When queue processing is enabled, dispatch a job and return immediately.
            if ($module->useQueue) {
                Yii::$app->get($module->queueComponent)->push(new ImportOrderBatchJob([
                    'limit'  => $this->limit,
                    'cursor' => $this->cursor,
                    'dryRun' => $this->dryRun,
                ]));

                $this->stdout("ImportOrderBatchJob dispatched to queue '{$module->queueComponent}'.\n");
                return ExitCode::OK;
            }

            $service = $module->createOrderImportService();
            $summary = $service->run($this->cursor, $this->limit, $this->dryRun);
            $this->stdout(Json::encode($summary, JSON_PRETTY_PRINT) . PHP_EOL);

            return $summary['failed'] > 0 ? ExitCode::UNSPECIFIED_ERROR : ExitCode::OK;
        } catch (\Throwable $throwable) {
            $this->stderr("Order import failed: {$throwable->getMessage()}\n");
            return ExitCode::UNSPECIFIED_ERROR;
        }
    }
}
