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

namespace PortalPeople\dx\jobs;

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

/**
 * ConsignmentJob
 *
 * Dispatches a single consignment to DX Despatch Manager 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['reference'] ?? 'unknown';
        Yii::info("DX ConsignmentJob: dispatching ref {$ref}", 'dx');

        try {
            /** @var \PortalPeople\dx\components\DxClient $client */
            $client = Yii::$app->dxClient;

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

            $tracking = implode(', ', $result['trackingNumbers'] ?? []);
            Yii::info(
                "DX ConsignmentJob: success for ref {$ref}. Tracking: {$tracking}",
                'dx'
            );
        } catch (\Exception $e) {
            Yii::error(
                "DX ConsignmentJob: exception for ref {$ref}: " . $e->getMessage(),
                'dx'
            );
            // Re-throw so the queue marks the job as failed and can retry
            throw $e;
        }
    }
}
