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

namespace PortalPeople\gforce\jobs;

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

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

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

    /** @var bool If true, commit=true is used (stores as live consignment). */
    public $commit = true;

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

        try {
            /** @var \PortalPeople\gforce\components\GForceClient $client */
            $client = Yii::$app->gforceClient;

            $result = $client->createConsignment($this->manifest, $this->commit);

            $statusCode = $result['Response']['Status']['Code']
                ?? ($result['Status'][0]['Code'] ?? 'ERROR');

            if ($statusCode === 'OK') {
                $responseId = $result['Response']['Detail']['ImportDetail']['ResponseID'] ?? 'n/a';
                Yii::info(
                    "ConsignmentJob: success for ref {$this->uniqueRef}. Response ID: {$responseId}",
                    'gforce'
                );
            } else {
                $description = $result['Response']['Status']['Description']
                    ?? ($result['Status'][0]['Description'] ?? 'unknown error');
                Yii::error(
                    "ConsignmentJob: API returned failure for ref {$this->uniqueRef}: {$description}",
                    'gforce'
                );
            }
        } catch (\Exception $e) {
            Yii::error(
                "ConsignmentJob: exception for ref {$this->uniqueRef}: " . $e->getMessage(),
                'gforce'
            );
            // Re-throw so the queue marks the job as failed and can retry
            throw $e;
        }
    }
}
