<?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;
use common\components\Tracing;

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

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

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

    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,
                    'exportToNetsuite' => $this->exportToNetsuite,
                    'ackVirtualStock' => $this->ackVirtualStock,
                ]));
                $this->stdout("ImportOrderBatchJob dispatched to queue '{$module->queueComponent}'.\n");
                return ExitCode::OK;
            }

            $service = $module->createOrderImportService();
            $summary = $service->run($this->cursor, $this->limit, $this->dryRun);
         
            // If queueing is disabled but export/ack flags requested, perform post-import processing locally
            if (($this->exportToNetsuite || $this->ackVirtualStock) && !empty($summary['processed'])) {
                foreach ($summary['processed'] as $proc) {
                    $cartId = $proc['cartId'] ?? null;
                    $orderNo = $proc['orderNo'] ?? null;
                    if (empty($cartId)) {
                        $orderNo = $proc['orderNo'] ?? 'unknown';
                        Yii::warning('OrderImportController: processed entry missing cartId for order ' . $orderNo, 'virtualstock');
                        continue;
                    }
                    $cart = \PortalPeople\virtualstock\models\Cart::findOne($cartId);
                    if (!$cart) {
                        Yii::warning('OrderImportController: cart not found: ' . $cartId, 'virtualstock');
                        continue;
                    }

                    if ($this->exportToNetsuite) {
                        try {
                            if (Yii::$app->has('netsuitequeue') && class_exists('\\PortalPeople\\netsuite\\jobs\\Sendtonetsuite')) {
                                Yii::info('OrderImportController: enqueueing Sendtonetsuite job for cart ' . $cartId, 'virtualstock');
                                Yii::$app->netsuitequeue->push(new \PortalPeople\netsuite\jobs\Sendtonetsuite(['id' => $cart->id]));
                            } elseif (class_exists('\\PortalPeople\\netsuite\\components\\NetSuite')) {
                                Yii::info('OrderImportController: calling NetSuite::SendOrderToNetsuite for cart ' . $cartId, 'virtualstock');
                                \PortalPeople\netsuite\components\NetSuite::SendOrderToNetsuite($cart);
                            } elseif (class_exists('\\backend\\models\\Netsuite')) {
                                Yii::info('OrderImportController: legacy backend Netsuite::createso for cart ' . $cartId, 'virtualstock');
                                \backend\models\Netsuite::createso($cart->id);
                            } else {
                                Yii::warning('OrderImportController: NetSuite integration not available, skipping export', 'virtualstock');
                            }
                        } catch (\Throwable $e) {
                            Yii::error('OrderImportController: NetSuite export failed for cart ' . $cartId . ': ' . $e->getMessage(), 'virtualstock');
                        }
                    }

                    if ($this->ackVirtualStock) {
                        try {
                            $vsService = $module->createVirtualStockService();
                            $resp = $vsService->acknowledgeOrderFromCart($cart);
                            $respStr = is_string($resp) ? $resp : json_encode($resp);
                            Yii::info('OrderImportController: VirtualStock acknowledge response for cart ' . $cartId, 'virtualstock');
                            Yii::debug('OrderImportController ack response: ' . $respStr, 'virtualstock');
                        } catch (\Throwable $e) {
                            Yii::error('OrderImportController: VirtualStock acknowledge failed for cart ' . $cartId, 'virtualstock');
                            Yii::error('OrderImportController: error: ' . $e->getMessage(), 'virtualstock');
                        }
                    }
                }
            }
            $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;
        }
    }

    public function actionPurgeOld() {
        $carts = \backend\models\Cartsbe::find()->select('id')->all();
        \backend\models\Cartlines::deleteAll(['not in', 'basketid' => $carts]);
        //\backend\models\Paymentresponsesbe::deleteAll(['not in', 'basketid' => $carts]);
        //\backend\models\Shipment::deleteAll(['not in', 'cart_id' => $carts]);
        //\backend\models\ActionLog::deleteAll(['not in', 'relatedid' => $carts]);
        //\backend\models\Shipment::deleteAll(['not in', 'relatedid' => $carts]);
    }
        
     public function actionStart() {
        $module = Yii::$app->getModule('virtualstock');
        
        if ($module->testMode == true) {
            \yii\helpers\Console::output("Test Mode is enabled. Orders will be removed.");
            $carts = \backend\models\Cartsbe::find()->where(['account_code' => 'SCR001'])->all();
            foreach ($carts as $cart) {
                \backend\models\Cartlines::deleteAll(['basketid' => $cart->id]);
                \backend\models\Paymentresponsesbe::deleteAll(['basketid' => $cart->id]);
                \backend\models\Shipment::deleteAll(['cart_id' => $cart->id]);
                \backend\models\ActionLog::deleteAll(['relatedid' => $cart->id]);
                \backend\models\Shipment::deleteAll(['relatedid' => $cart->id]);
                $cart->purge();
            }
        }
        Yii::$app->queue
            ->jobname('ScrewFix - Import Orders')
            ->push(new ImportOrderBatchJob([
                    'limit' => 50,
                    'dryRun' => 0,
                    'exportToNetsuite' => 1,
                    'ackVirtualStock' => 0,
                ])
            );
    }
}
