<?php

namespace App\Jobs;

use App\Models\TrackingSave;
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 TrackSaveJob 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 bool $isPremiumExport,
        private Carbon $actionAt,
        private ?string $userAgent,
        private ?string $ipAddress,
        private string $platform
    ) {
        $this->onQueue('tracking');
    }

    public function handle(): void
    {
        try {
            TrackingSave::create([
                'device_id' => $this->deviceId,
                'meme_id' => $this->memeId,
                'meme_media_id' => $this->memeMediaId,
                'background_media_id' => $this->backgroundMediaId,
                'caption_texts' => $this->captionTexts,
                'is_premium_export' => $this->isPremiumExport,
                'action_at' => $this->actionAt,
                'user_agent' => $this->userAgent,
                'ip_address' => $this->ipAddress,
                'platform' => $this->platform,
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to track save', [
                'device_id' => $this->deviceId,
                'meme_id' => $this->memeId,
                'meme_media_id' => $this->memeMediaId,
                'background_media_id' => $this->backgroundMediaId,
                'error' => $e->getMessage(),
            ]);

            throw $e;
        }
    }

    public function failed(\Throwable $exception): void
    {
        Log::error('TrackSaveJob failed permanently', [
            'device_id' => $this->deviceId,
            'meme_id' => $this->memeId,
            'meme_media_id' => $this->memeMediaId,
            'background_media_id' => $this->backgroundMediaId,
            'exception' => $exception->getMessage(),
        ]);
    }
}
