<?php

namespace App\Jobs;

use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use App\Models\Website;
use App\Services\ScreenshotService;
use Throwable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Foundation\Bus\Dispatchable;

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

    /**
     * Create a new job instance.
     */
    public function __construct(public Website $website)
    {
    }

    /**
     * Execute the job.
     */
    public function handle(ScreenshotService $screenshotService): void
    {
        try {
            $this->website->update(['status' => 'processing']);

            $path = $screenshotService->capture($this->website);

            $this->website->update([
                'status' => 'completed',
                'screenshot_path' => $path,
                'last_scanned_at' => now(),
                'error_message' => null,
            ]);
        } catch (Throwable $e) {
            $this->website->update([
                'status' => 'failed',
                'error_message' => $e->getMessage(),
                'last_scanned_at' => now(),
            ]);
        }
    }
}
