<?php

namespace PortalPeople\virtualstock\services;

use Yii;
use yii\base\BaseObject;
use backend\models\ActionLog;
use PortalPeople\virtualstock\components\VirtualStockClient;
use PortalPeople\virtualstock\models\Cart;
use common\components\Tracing;

class VirtualStockService extends BaseObject
{
    public VirtualStockClient $client;
    public OrderService $orderService;
    public ProductService $productService;

    public function init(): void
    {
        parent::init();
    }

    /**
     * Update remote order using payload or status and persist response on the cart.
     */
    public function updateOrderFromCart(Cart $cart, $payload, ?string $status = null)
    {
        $orderNo = $cart->ordernumber ?? null;
        if (empty($orderNo)) {
            throw new \InvalidArgumentException('No VirtualStock order identifier on cart');
        }

      
        $payloadData = $this->orderService->prepareUpdatePayload($payload);
        $send = [];
        if ($status !== null) {
            $send['status'] = (string)$status;
        }
        if ($payloadData !== []) {
            $send = array_merge($send, $payloadData);
        }

        if ($send === []) {
            throw new \InvalidArgumentException('Nothing to send');
        }

        try {
            $resp = $this->client->updateOrder($orderNo, $send);
            Cart::appendVirtualStockApiResponse($cart, $resp);
        } catch (\Throwable $e) {
            throw $e;
        }

        // Attempt to map response into cart when mappable
        if (is_array($resp) && count($resp) > 0) {
            try {
                Cart::applyVirtualStockOrderData($cart, $resp, $orderNo, Yii::$app->getModule('virtualstock'));
                $cart->save(false);
            } catch (\Throwable $e) {
                Yii::warning('Failed to map update response into cart: ' . $e->getMessage(), 'virtualstock');
            }
        }

        return $resp;
    }

    public function acknowledgeOrderFromCart(\backend\models\Cartsbe|Cart $cart)
    {
        $orderNo = json_decode($cart->imported_data ?? '{}', true)['url'] ?? $cart->ordernumber ?? null;
        if (empty($orderNo)) {
            throw new \InvalidArgumentException('No VirtualStock order identifier on cart');
        }
        if ($cart->data->virtualstock->acknowledged === true) {
            return false; // Already acknowledged, no action needed
        }
        try {
            ActionLog::create(['class' => self::class, 'action' => 'import', 'type' => 'Info', 'relatedid' => $cart->id, 'message' => "VirtualStock - Acknowledging cart #{$cart->orderref}"]);
            Yii::$app->request->isConsoleRequest ? \yii\helpers\Console::output("VirtualStock acknowledging for cart {$cart->id}: ") : null;    
            $payload = $this->orderService->buildAcknowledgePayloadFromCart($cart);
            Yii::$app->request->isConsoleRequest ? \yii\helpers\Console::output("Payload: " . json_encode($payload)) : null;
            $resp = $this->client->acknowledgeOrder($orderNo, $payload ?? []);
            Cart::appendVirtualStockApiResponse($cart, $resp);
            $cart->updateVSstatus('Acknowledged');
            ActionLog::create(['class' => self::class, 'action' => 'import', 'type' => 'Info', 'relatedid' => $cart->id, 'message' => "VirtualStock - Acknowledged cart #{$cart->orderref}"]);
            return $resp;
        } catch (\Throwable $e) {
            ActionLog::create(['class' => self::class, 'action' => 'import', 'type' => 'Error', 'relatedid' => $cart->id, 'message' => "VirtualStock - Acknowledging cart failed #{$cart->orderref}: \n" . $e->getMessage()]);
            throw $e;
        }
    }

    public function dispatchOrderFromCart(\backend\models\Cartsbe|Cart $cart)
    {
        is_a($cart, \backend\models\Cartsbe::class) ? $cart = Cart::findOne($cart->id) : null;
        $orderNo = json_decode($cart->imported_data ?? '{}', true)['url'] ?? $cart->ordernumber ?? null;
        if (empty($orderNo)) {
            throw new \InvalidArgumentException('No VirtualStock order identifier on cart');
        }
        
        
        if ($cart->data->virtualstock->dispatched === true) {
            return false; // Already dispatched, no action needed
        }

        try {
            ActionLog::create(['class' => self::class, 'action' => 'import', 'type' => 'Info', 'relatedid' => $cart->id, 'message' => "VirtualStock - Dispatching cart #{$cart->orderref}"]);
            $payload = $this->orderService->buildDispatchPayloadFromCart($cart);
            $resp = $this->client->dispatchOrder($orderNo, $payload);
            Cart::appendVirtualStockApiResponse($cart, $resp);
            $cart->updateVSstatus('Dispatched');
            \Yii::$app->trigger('cart-dispatch-email-'.$cart->account_code, new \common\events\UserDataEvent(['model' => $cart, 'customData' => ['new' => true]]));
            ActionLog::create(['class' => self::class, 'action' => 'dispatch', 'type' => 'Info', 'relatedid' => $cart->id, 'message' => "VirtualStock - Dispatched cart #{$cart->orderref}"]);
            return $resp;
        } catch (\Throwable $e) {
            yii::warning($e, 'Error');
            ActionLog::create(['class' => self::class, 'action' => 'dispatch', 'type' => 'Error', 'relatedid' => $cart->id, 'message' => "VirtualStock - Dispatching cart #{$cart->orderref} failed : \n" . $e->getMessage()]);
            throw $e;
        }
    }
}
