<?php
/**
 * Consignment Queue Job – UPN Delivery Module
 *
 * @category    PortalPeople
 * @package     UPN
 * @author      Portal People Development Team
 * @copyright   Copyright (c) 2026 Portal People (https://portalpeople.co.uk)
 */

namespace PortalPeople\upn\jobs;

use Yii;
use yii\base\BaseObject;
use yii\queue\JobInterface;

/**
 * ConsignmentJob
 *
 * Dispatches a single pallet consignment to UPN asynchronously via
 * the Yii2 queue component.
 */
class ConsignmentJob extends BaseObject implements JobInterface
{
    /** @var array Full consignment data (from ConsignmentForm::getConsignmentData()). */
    public $consignmentData = [];

    /**
     * Execute the job.
     *
     * @param \yii\queue\Queue $queue
     */
    public function execute($queue)
    {
        $ref = $this->consignmentData['CustRef'] ?? 'unknown';
        Yii::info("UPN ConsignmentJob: dispatching ref {$ref}", 'upn');

        try {
            /** @var \PortalPeople\upn\components\UpnClient $client */
            $client = Yii::$app->upnClient;

            $result = $client->addConsignment($this->consignmentData);

            $conBarcode = is_object($result)
                ? ($result->AddConsignment_V4Result ?? ($result->ConBarcode ?? ''))
                : (is_array($result) ? ($result['ConBarcode'] ?? '') : '');

            Yii::info(
                "UPN ConsignmentJob: success for ref {$ref}. Barcode: {$conBarcode}",
                'upn'
            );
        } catch (\Exception $e) {
            Yii::error(
                "UPN ConsignmentJob: exception for ref {$ref}: " . $e->getMessage(),
                'upn'
            );
            // Re-throw so the queue marks the job as failed and can retry
            throw $e;
        }
    }
}
