<?php

namespace App\Listeners;

use App\Events\OrderCreated;
use App\Services\QrStickerService;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;

class GenerateQrCodeOnOrderCreated
{
    /**
     * Handle the event.
     */
    public function handle(OrderCreated $event): void
    {
        $order = $event->order;

        try {
            // Generate secure token if not already set
            if (! $order->qr_token) {
                $order->qr_token = Str::random(32);
                $order->qr_generated_at = now();
                $order->save();
            }

            Log::debug('Generating QR sticker', [
                'order_uuid' => $order->uuid,
                'order_number' => $order->order_number,
            ]);

            // Generate both SVG (web) and PDF (print) stickers
            $service = new QrStickerService();
            $paths = $service->generateSticker($order);

            Log::info('QR sticker generated successfully', [
                'order_uuid' => $order->uuid,
                'svg_path' => $paths['svg_path'],
                'pdf_path' => $paths['pdf_path'],
                'token' => substr($order->qr_token, 0, 8) . '...',
            ]);
        } catch (\Exception $e) {
            Log::error('Failed to generate QR code', [
                'order_uuid' => $order->uuid,
                'error' => $e->getMessage(),
            ]);
        }
    }
}
