<?php

declare(strict_types=1);

namespace ImovelZapAi\Documents\Application\Services;

use BaconQrCode\Renderer\Image\SvgImageBackEnd;
use BaconQrCode\Renderer\ImageRenderer;
use BaconQrCode\Renderer\RendererStyle\RendererStyle;
use BaconQrCode\Writer;
use Dompdf\Dompdf;
use Dompdf\Options;
use Illuminate\Support\Facades\Storage;
use ImovelZapAi\Documents\Infrastructure\Persistence\Eloquent\BusinessDocumentModel;
use ImovelZapAi\Documents\Infrastructure\Persistence\Eloquent\DocumentVersionModel;

final class DocumentPdfGenerator
{
    public function disk(): string
    {
        return (string) config('documents.disk', 'local');
    }

    /**
     * @return array{disk: string, path: string}
     */
    public function generate(BusinessDocumentModel $document, DocumentVersionModel $version, string $publicUrl): array
    {
        $qrSvg = $this->qrSvg($publicUrl !== '' ? $publicUrl : $version->validation_code);
        $html = view('documents.pdf', [
            'document' => $document,
            'version' => $version,
            'qrSvg' => $qrSvg,
            'company' => $version->snapshot['company_name'] ?? '',
            'body' => $version->html_body,
        ])->render();

        $options = new Options;
        $options->set('isRemoteEnabled', true);
        $options->set('defaultFont', 'DejaVu Sans');
        $dompdf = new Dompdf($options);
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4');
        $dompdf->render();

        $path = sprintf(
            'documents/%s/%s/v%s-%s.pdf',
            $document->tenant_id,
            $document->id,
            $version->version,
            $version->validation_code,
        );

        Storage::disk($this->disk())->put($path, $dompdf->output());

        return ['disk' => $this->disk(), 'path' => $path];
    }

    private function qrSvg(string $payload): string
    {
        $renderer = new ImageRenderer(new RendererStyle(120), new SvgImageBackEnd);
        $writer = new Writer($renderer);

        return $writer->writeString($payload);
    }
}
