<?php

namespace App\Jobs;

use App\Services\AI\PuppeteerMetaAdLibraryProvider;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\File;
use Throwable;

class ScrapeMetaAdLibraryJob implements ShouldQueue
{
    use Queueable;

    public int $tries = 1;

    public int $timeout = 180;

    public function __construct(
        public string $url,
        public string $outPath,
    ) {}

    public function handle(PuppeteerMetaAdLibraryProvider $provider): void
    {
        $provider->executeQueuedScrape($this->url, $this->outPath);
    }

    public function failed(?Throwable $exception): void
    {
        File::ensureDirectoryExists(dirname($this->outPath));
        File::put($this->outPath, json_encode([
            'status' => 'FAILED',
            'ads' => [],
            'error' => $exception?->getMessage() ?: 'Puppeteer Meta Ad Library search failed.',
        ], JSON_THROW_ON_ERROR));
    }
}
