<?php

namespace Tests\Unit\Jobs;

use App\Jobs\ScrapeMetaAdLibraryJob;
use App\Services\AI\PuppeteerMetaAdLibraryProvider;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Process;
use Tests\TestCase;

class ScrapeMetaAdLibraryJobTest extends TestCase
{
    public function test_it_runs_node_like_catalog_listing_scrape(): void
    {
        config([
            'creative.puppeteer_ad_library.enabled' => true,
            'creative.puppeteer_ad_library.node_binary' => 'node',
            'creative.puppeteer_ad_library.script' => 'scripts/ad-library/scrape-ad-library.js',
            'creative.puppeteer_ad_library.timeout_seconds' => 180,
            'creative.puppeteer_ad_library.headless' => 'true',
            'creative.puppeteer_ad_library.max_ads' => 20,
        ]);

        $outPath = storage_path('app/private/ad-library/job-test.json');
        File::ensureDirectoryExists(dirname($outPath));
        File::put($outPath, json_encode([
            'status' => 'RUNNING',
            'ads' => [],
            'error' => null,
        ], JSON_THROW_ON_ERROR));

        Process::preventStrayProcesses();
        Process::fake(function () use ($outPath) {
            File::put($outPath, json_encode([
                'status' => 'SUCCEEDED',
                'ads' => [['id' => '1', 'pageName' => 'adidas']],
                'error' => null,
            ], JSON_THROW_ON_ERROR));

            return Process::result('');
        });

        (new ScrapeMetaAdLibraryJob(
            'https://www.facebook.com/ads/library/?q=adidas&country=US',
            $outPath,
        ))->handle(new PuppeteerMetaAdLibraryProvider);

        $this->assertSame('SUCCEEDED', json_decode(File::get($outPath), true)['status']);

        Process::assertRan(function ($process): bool {
            $command = is_array($process->command) ? implode(' ', $process->command) : $process->command;

            return str_contains($command, 'scrape-ad-library.js')
                && str_contains($command, '--out')
                && ($process->environment['AD_LIBRARY_PUPPETEER_HEADLESS'] ?? null) === 'true'
                && ! str_contains($command, 'start /B');
        });
    }

    public function test_it_marks_the_run_failed_when_the_job_fails(): void
    {
        $outPath = storage_path('app/private/ad-library/job-failed.json');
        File::ensureDirectoryExists(dirname($outPath));

        (new ScrapeMetaAdLibraryJob(
            'https://www.facebook.com/ads/library/?q=adidas',
            $outPath,
        ))->failed(new \RuntimeException('queue worker crashed'));

        $payload = json_decode(File::get($outPath), true);

        $this->assertSame('FAILED', $payload['status']);
        $this->assertSame('queue worker crashed', $payload['error']);
    }
}
