<?php

namespace App\Jobs;

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

    public function __construct(
        private string $deviceId,
        private string $searchType,
        private string $searchQuery,
        private ?array $searchFilters,
        private Carbon $actionAt,
        private ?string $userAgent,
        private ?string $ipAddress,
        private string $platform
    ) {
        $this->onQueue('tracking');
    }

    public function handle(): void
    {
        try {
            TrackingSearch::create([
                'device_id' => $this->deviceId,
                'search_type' => $this->searchType,
                'search_query' => $this->searchQuery,
                'search_filters' => $this->searchFilters,
                'action_at' => $this->actionAt,
                'user_agent' => $this->userAgent,
                'ip_address' => $this->ipAddress,
                'platform' => $this->platform,
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to track search', [
                'device_id' => $this->deviceId,
                'search_type' => $this->searchType,
                'search_query' => $this->searchQuery,
                'error' => $e->getMessage(),
            ]);
            
            throw $e;
        }
    }

    public function failed(\Throwable $exception): void
    {
        Log::error('TrackSearchJob failed permanently', [
            'device_id' => $this->deviceId,
            'search_type' => $this->searchType,
            'search_query' => $this->searchQuery,
            'exception' => $exception->getMessage(),
        ]);
    }
}