<?php

namespace App\Jobs;

use App\Models\Invoice;
use Barryvdh\DomPDF\Facade\Pdf;
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\Storage;

class GenerateInvoicePdfJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public function __construct(private string $invoiceId) {}

    public function handle(): void
    {
        $invoice = Invoice::with(['customer', 'items', 'vehicle', 'payments'])->find($this->invoiceId);
        if (! $invoice) {
            return;
        }

        $pdf = Pdf::loadView('pdf.invoice', compact('invoice'))->setPaper('a4');
        Storage::disk('local')->put($this->pdfPath(), $pdf->output());
    }

    public static function pathFor(string $invoiceId): string
    {
        return "reports/invoices/{$invoiceId}.pdf";
    }

    private function pdfPath(): string
    {
        return self::pathFor($this->invoiceId);
    }
}
