<?php

namespace App\Jobs;

use App\Models\TrackingContentSelection;
use Carbon\Carbon;
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 TrackContentSelectionJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct(
        private string $deviceId,
        private string $contentType,
        private int $contentId,
        private string $contentName,
        private string $selectionMethod,
        private ?string $searchQuery,
        private Carbon $actionAt,
        private ?string $userAgent,
        private ?string $ipAddress,
        private string $platform
    ) {
        $this->onQueue('tracking');
    }

    public function handle(): void
    {
        try {
            TrackingContentSelection::create([
                'device_id' => $this->deviceId,
                'content_type' => $this->contentType,
                'content_id' => $this->contentId,
                'content_name' => $this->contentName,
                'selection_method' => $this->selectionMethod,
                'search_query' => $this->searchQuery,
                'action_at' => $this->actionAt,
                'user_agent' => $this->userAgent,
                'ip_address' => $this->ipAddress,
                'platform' => $this->platform,
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to track content selection', [
                'device_id' => $this->deviceId,
                'content_type' => $this->contentType,
                'content_id' => $this->contentId,
                'error' => $e->getMessage(),
            ]);
            
            throw $e;
        }
    }

    public function failed(\Throwable $exception): void
    {
        Log::error('TrackContentSelectionJob failed permanently', [
            'device_id' => $this->deviceId,
            'content_type' => $this->contentType,
            'content_id' => $this->contentId,
            'exception' => $exception->getMessage(),
        ]);
    }
}