<?php

declare(strict_types=1);

namespace ImovelZapAi\Proposals\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\Proposals\Infrastructure\Persistence\Eloquent\ProposalModel;
use ImovelZapAi\Proposals\Infrastructure\Persistence\Eloquent\ProposalVersionModel;

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

    /**
     * @return array{disk: string, path: string}
     */
    public function generate(ProposalModel $proposal, ProposalVersionModel $version, string $publicUrl): array
    {
        $qrSvg = $this->qrSvg($publicUrl !== '' ? $publicUrl : $version->validation_code);
        $html = view('proposals.pdf', [
            'proposal' => $proposal,
            '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(
            'proposals/%s/%s/v%s-%s.pdf',
            $proposal->tenant_id,
            $proposal->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);
    }
}
