<?php

namespace PortalPeople\magento\services;

use PortalPeople\magento\Module;
use PortalPeople\magento\models\Cart;
use Yii;

class OrderImportService
{
    public function getConfiguredModule(): ?Module
    {
        $module = Yii::$app->getModule('magento');
        if (!$module instanceof Module || !$module->isConfigured()) {
            return null;
        }

        return $module;
    }

    public function getOrder(Module $module, int $id): array
    {
        $client = new MagentoClient((string) $module->apiUrl, (string) $module->accessToken);

        return $client->getOrder($id);
    }

    public function importOrder(array $order): array
    {
        $result = Cart::newMagentoOrder($order);

        return [
            'result' => $result,
            'orderNo' => (string) ($order['increment_id'] ?? $order['orderNo'] ?? ''),
        ];
    }

    public function importOrders(array $orders): array
    {
        $imported = 0;
        $failed = 0;
        $errors = [];

        foreach ($orders as $item) {
            if (!is_array($item)) {
                continue;
            }

            try {
                Cart::newMagentoOrder($item);
                $imported++;
            } catch (\Throwable $e) {
                $failed++;
                $errors[] = $this->buildImportDebug($item, $e);
                if (Yii::$app instanceof \yii\console\Application) {
                    \yii\helpers\Console::output("Magento order import failed: " . $e->getMessage());
                }
                Yii::error([
                    'message' => 'Magento order import failed: ' . $e->getMessage(),
                    'debug' => end($errors),
                ], 'magento.import');
            }
        }

        return [
            'imported' => $imported,
            'failed' => $failed,
            'errors' => $errors,
        ];
    }

    public function importPayments(array $payments): array
    {
        $updated = 0;
        $skipped = 0;

        foreach ($payments as $payment) {
            if (!is_array($payment)) {
                continue;
            }

            try {
                $result = Cart::updateMagentoPayment($payment);
                if (($result['updated'] ?? false) === true) {
                    $updated++;
                } else {
                    $skipped++;
                }
            } catch (\Throwable $e) {
                $skipped++;
                Yii::error('Magento payment import failed: ' . $e->getMessage(), 'magento');
            }
        }

        return [
            'updated' => $updated,
            'skipped' => $skipped,
        ];
    }

    public function buildImportDebug(array $order, \Throwable $exception): array
    {
        return [
            'orderId' => $order['entity_id'] ?? $order['orderId'] ?? null,
            'orderNo' => $order['increment_id'] ?? $order['orderNo'] ?? null,
            'exception' => [
                'class' => get_class($exception),
                'message' => $exception->getMessage(),
                'file' => $exception->getFile(),
                'line' => $exception->getLine(),
            ],
            'arrayFields' => $this->findArrayFields($order),
            'fieldTypes' => $this->summarizeFieldTypes($order),
        ];
    }

    private function findArrayFields(array $data): array
    {
        $fields = [];

        foreach ($data as $key => $value) {
            if (is_array($value)) {
                $fields[] = $key;
            }
        }

        return $fields;
    }

    private function summarizeFieldTypes(array $data): array
    {
        $summary = [];

        foreach ($data as $key => $value) {
            $summary[$key] = is_array($value) ? 'array' : (is_object($value) ? get_class($value) : gettype($value));
        }

        return $summary;
    }
}