<?php

namespace App\Jobs;

use App\Actions\UpdateShopifyCollectionSalePriceFrontGold;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class UpdateCollectionSalePriceJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected $requestData;
    protected $productsData;
    protected $collectionTitle;
    protected $progressId;

    /**
     * Create a new job instance.
     */
    public function __construct(array $requestData, array $productsData, string $collectionTitle, string $progressId)
    {
        $this->requestData = $requestData;
        $this->productsData = $productsData;
        $this->collectionTitle = $collectionTitle;
        $this->progressId = $progressId;
    }

    /**
     * Execute the job.
     */
    public function handle(): void
    {
        try {
            // Create a new Request with all the data
            // Include pre-obtained data so Action doesn't query Shopify again
            $request = new Request($this->requestData);
            $request->merge([
                '_products_data' => $this->productsData,
                '_collection_title' => $this->collectionTitle,
                '_progress_id' => $this->progressId,
            ]);

            // Call the Action with pre-obtained data
            // The Action will use the data instead of querying Shopify
            (new UpdateShopifyCollectionSalePriceFrontGold())($request, true);
        } catch (\Throwable $th) {
            Log::error("UpdateCollectionSalePriceJob failed", [
                'error' => $th->getMessage(),
                'trace' => $th->getTraceAsString(),
                'progress_id' => $this->progressId,
                'file' => $th->getFile(),
                'line' => $th->getLine(),
            ]);
            throw $th; // Re-throw to let Laravel handle job retries
        }
    }
}
