<?php

namespace App\Jobs;

use App\Services\BadhonsworldService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Log;

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

    /**
     * The number of seconds the job can run before timing out.
     *
     * @var int
     */
    public $timeout = 1800; // 30 minutes for large syncs with images

    protected int $categoryId;

    /**
     * Create a new job instance.
     */
    public function __construct(int $categoryId)
    {
        $this->categoryId = $categoryId;
    }

    /**
     * Execute the job.
     */
    public function handle(BadhonsworldService $service): void
    {
        Log::info("BadhonsworldBulkImportJob: Starting bulk import under category ID: {$this->categoryId}");
        
        try {
            $importedCount = $service->bulkImportAll($this->categoryId, function ($currentCount) {
                if ($currentCount % 10 === 0) {
                    Log::info("BadhonsworldBulkImportJob: Imported {$currentCount} products so far...");
                }
            });
            Log::info("BadhonsworldBulkImportJob: Finished bulk import. Total products imported/updated: {$importedCount}");
        } catch (\Exception $e) {
            Log::error("BadhonsworldBulkImportJob: Error during import: " . $e->getMessage());
            throw $e;
        }
    }
}
