<?php

namespace PortalPeople\magento\commands;

use Yii;
use yii\console\Controller;
use PortalPeople\magento\models\Cart;
use PortalPeople\magento\Module;
use PortalPeople\magento\services\MagentoClient;

class ImportMagentoOrdersController extends Controller
{
    public $baseUrl;
    public $accessToken;
    public $limit = 20;

    public function options($actionID)
    {
        return ['baseUrl', 'accessToken', 'limit'];
    }

    public function actionRun()
    {
        $module = Yii::$app->getModule('magento');

        if (!$module instanceof Module || !$module->isConfigured()) {
            if (empty($this->baseUrl) || empty($this->accessToken)) {
                $this->stderr("Please provide --baseUrl and --accessToken or configure the magento module first.\n");
                return 1;
            }
        }

        $baseUrl = $module->apiUrl ?? $this->baseUrl;
        $accessToken = $module->accessToken ?? $this->accessToken;

        $client = new MagentoClient((string) $baseUrl, (string) $accessToken);
        $this->stdout("Fetching up to {$this->limit} orders from {$baseUrl}...\n");

        $orders = $client->getOrders(['searchCriteria[pageSize]' => (int) $this->limit]);
        $items = $orders['items'] ?? [];

        $imported = 0;
        $failed = 0;

        foreach ($items as $item) {
            try {
                Cart::newMagentoOrder($item);
                $imported++;
            } catch (\Throwable $e) {
                $failed++;
                $orderId = (string) ($item['entity_id'] ?? 'unknown');
                $this->stderr('Failed to import order ' . $orderId . ': ' . $e->getMessage() . "\n");
            }
        }

        $this->stdout("Imported {$imported} order(s); failed {$failed}.\n");
        return $failed > 0 ? 1 : 0;
    }
}
