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

namespace PortalPeople\palletforce\jobs;

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

/**
 * ConsignmentJob
 *
 * Dispatches a single consignment to Palletforce asynchronously via the
 * Yii2 queue component.
 *
 * Note: Palletforce enforces a rate limit of one call every 30 minutes.
 * Consider configuring your queue worker delay accordingly.
 */
class ConsignmentJob extends BaseObject implements JobInterface
{
    /** @var array Consignment data (from ConsignmentForm::getConsignmentData()). */
    public $consignmentData = [];

    /** @var array Collection address (from ConsignmentForm::getCollectionAddress()). */
    public $collectionAddress = [];

    /** @var array Delivery address (from ConsignmentForm::getDeliveryAddress()). */
    public $deliveryAddress = [];

    /** @var string Unique transaction reference. */
    public $uniqueRef = '';

    /**
     * Execute the job.
     *
     * @param \yii\queue\Queue $queue
     */
    public function execute($queue)
    {
        Yii::info("ConsignmentJob: dispatching ref {$this->uniqueRef}", 'palletforce');

        try {
            /** @var \PortalPeople\palletforce\components\PalletforceClient $client */
            $client = Yii::$app->palletforceClient;

            $result = $client->uploadManifest(
                $this->consignmentData,
                $this->uniqueRef,
                $this->collectionAddress,
                $this->deliveryAddress
            );

            if ($result['Success'] ?? false) {
                Yii::info(
                    "ConsignmentJob: success for ref {$this->uniqueRef}. Tracking: "
                    . implode(', ', $result['TrackingCodes'] ?? []),
                    'palletforce'
                );
            } else {
                Yii::error(
                    "ConsignmentJob: API returned failure for ref {$this->uniqueRef}: "
                    . ($result['Message'] ?? 'unknown error')
                    . " (ErrorCode: " . ($result['ErrorCode'] ?? 'n/a') . ")",
                    'palletforce'
                );
            }
        } catch (\Exception $e) {
            Yii::error(
                "ConsignmentJob: exception for ref {$this->uniqueRef}: " . $e->getMessage(),
                'palletforce'
            );
            // Re-throw so the queue marks the job as failed and can retry
            throw $e;
        }
    }
}
