<?php

namespace App\Jobs;

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

    public function __construct(
        private string $deviceId,
        private ?int $memeId,
        private ?int $memeMediaId,
        private ?int $backgroundMediaId,
        private array $captionTexts,
        private string $exportFormat,
        private string $exportQuality,
        private Carbon $actionAt,
        private ?string $userAgent,
        private ?string $ipAddress,
        private string $platform
    ) {
        $this->onQueue('tracking');
    }

    public function handle(): int
    {
        try {
            $trackingExport = TrackingExport::create([
                'device_id' => $this->deviceId,
                'meme_id' => $this->memeId,
                'meme_media_id' => $this->memeMediaId,
                'background_media_id' => $this->backgroundMediaId,
                'caption_texts' => $this->captionTexts,
                'export_format' => $this->exportFormat,
                'export_quality' => $this->exportQuality,
                'export_status' => 'initiated',
                'action_at' => $this->actionAt,
                'user_agent' => $this->userAgent,
                'ip_address' => $this->ipAddress,
                'platform' => $this->platform,
            ]);

            return $trackingExport->id;
        } catch (\Exception $e) {
            Log::error('Failed to track export', [
                'device_id' => $this->deviceId,
                'meme_id' => $this->memeId,
                'export_format' => $this->exportFormat,
                'error' => $e->getMessage(),
            ]);
            
            throw $e;
        }
    }

    public function failed(\Throwable $exception): void
    {
        Log::error('TrackExportJob failed permanently', [
            'device_id' => $this->deviceId,
            'meme_id' => $this->memeId,
            'export_format' => $this->exportFormat,
            'exception' => $exception->getMessage(),
        ]);
    }
}