<?php

namespace App\Jobs;

use App\Models\Order;
use App\Services\PDFService;
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 GeneratePDFJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * The number of times the job may be attempted.
     *
     * @var int
     */
    public $tries = 3;

    /**
     * The number of seconds the job can run before timing out.
     *
     * @var int
     */
    public $timeout = 120;

    /**
     * Create a new job instance.
     */
    public function __construct(
        public Order $order
    ) {}

    /**
     * Execute the job.
     */
    public function handle(PDFService $pdfService): void
    {
        try {
            Log::info("Generating PDF for order", ['order_id' => $this->order->id]);

            $this->order->markAsProcessing();

            $pdfService->generateOrderPDF($this->order);

            Log::info("PDF generated successfully", ['order_id' => $this->order->id]);

        } catch (\Exception $e) {
            Log::error("PDF generation failed", [
                'order_id' => $this->order->id,
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
            ]);

            $this->order->markAsFailed("PDF generation failed: " . $e->getMessage());

            throw $e;
        }
    }

    /**
     * Handle a job failure.
     */
    public function failed(\Throwable $exception): void
    {
        Log::error("PDF generation job failed after all retries", [
            'order_id' => $this->order->id,
            'error' => $exception->getMessage(),
        ]);

        $this->order->markAsFailed("PDF generation failed after {$this->tries} attempts");
    }
}
