<?php

namespace App\Jobs\Tracking;

use App\Services\Tracking\Contracts\TrackingProvider;
use App\Services\Tracking\TrackingEvent;
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 SendTrackingEventJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries = 3;
    public array $backoff = [10, 60, 300];

    /**
     * @param class-string<TrackingProvider> $providerClass
     */
    public function __construct(
        public string $providerClass,
        public TrackingEvent $event,
        public array $consentSnapshot = ['marketing' => true],
    ) {}

    public function handle(): void
    {
        if (!($this->consentSnapshot['marketing'] ?? false)) {
            return;
        }
        /** @var TrackingProvider $provider */
        $provider = app($this->providerClass);
        $provider->send($this->event);
    }

    public function failed(\Throwable $e): void
    {
        Log::channel('tracking')->error('SendTrackingEventJob permanently failed', [
            'provider' => $this->providerClass,
            'event' => $this->event->name,
            'event_id' => $this->event->eventId,
            'exception' => $e->getMessage(),
        ]);
    }
}
