<?php
/**
 * Product Sync Job for Queue Processing
 *
 * @category    PortalPeople
 * @package     Magento
 * @author      Portal People Development Team
 * @copyright   Copyright (c) 2025 Portal People (https://portalpeople.co.uk)
 */

namespace PortalPeople\magento\jobs;

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

/**
 * Product Sync Job
 * 
 * Handles asynchronous product synchronization to Magento
 */
class ProductSyncJob extends BaseObject implements JobInterface
{
    /**
     * @var int Product ID
     */
    public $productId;

    /**
     * @var array Product data
     */
    public $productData;

    /**
     * @var string Sync action (create|update|delete)
     */
    public $action;

    /**
     * Execute the job
     * 
     * @param \yii\queue\Queue $queue
     */
    public function execute($queue)
    {
        try {
            Yii::info("Processing sync job for product ID: {$this->productId}, Action: {$this->action}", 'magento-sync');

            $syncComponent = Yii::$app->magentoSync;
            
            if (!$syncComponent) {
                throw new \Exception('Magento sync component not configured');
            }

            // Find the product model
            $product = $this->findProduct();
            
            if (!$product && $this->action !== 'delete') {
                throw new \Exception("Product with ID {$this->productId} not found");
            }

            // Process the sync
            $result = $syncComponent->processSyncJob($product, $this->action);

            if ($result) {
                Yii::info("Successfully processed sync job for product ID: {$this->productId}", 'magento-sync');
            } else {
                throw new \Exception("Sync job failed for product ID: {$this->productId}");
            }

        } catch (\Exception $e) {
            Yii::error("Error processing sync job: " . $e->getMessage(), 'magento-sync');
            throw $e; // Re-throw to mark job as failed
        }
    }

    /**
     * Find product model by ID
     * 
     * @return \yii\db\ActiveRecord|null
     */
    protected function findProduct()
    {
        // Try to find the product using common model classes
        $possibleClasses = [
            'app\models\Product',
            'app\models\Products', 
            'common\models\Product',
            'common\models\Products',
            'backend\models\Product',
            'backend\models\Products'
        ];

        foreach ($possibleClasses as $class) {
            if (class_exists($class)) {
                try {
                    return $class::findOne($this->productId);
                } catch (\Exception $e) {
                    continue;
                }
            }
        }

        return null;
    }
}