<?php

namespace App\Jobs;

use App\Contracts\CreativeBriefResolver;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Support\Facades\Cache;
use Throwable;

class PrefetchCreativeBriefJob implements ShouldQueue
{
    use Queueable;

    public int $tries = 1;

    public int $timeout = 120;

    public function __construct(public string $url) {}

    public function handle(CreativeBriefResolver $briefResolver): void
    {
        try {
            $brief = $briefResolver->fromProductUrl($this->url);
            Cache::put(self::cacheKey($this->url), $brief->toArray(), now()->addMinutes(30));
        } catch (Throwable $e) {
            logger()->warning('Creative brief prefetch failed, will retry at generation time', [
                'url' => $this->url,
                'exception' => $e,
            ]);
        }
    }

    public static function cacheKey(string $url): string
    {
        return 'creative-brief:url:'.hash('sha256', trim($url));
    }
}
