<?php

namespace App\Services;

use App\Models\Tenant\InjectorProtocol;
use Spatie\Browsershot\Browsershot;

class InjectorProtocolPdfService
{
    public function render(InjectorProtocol $protocol): string
    {
        $html = view('pdf.injector-protocol', ['protocol' => $protocol->load('rows', 'master')])->render();

        $shot = Browsershot::html($html)
            ->format('A4')
            ->margins(12, 14, 12, 14)
            ->showBackground()
            ->waitUntilNetworkIdle();

        if ($node = env('BROWSERSHOT_NODE_BINARY')) {
            $shot->setNodeBinary($node);
        }
        if ($npm = env('BROWSERSHOT_NPM_BINARY')) {
            $shot->setNpmBinary($npm);
        }
        if ($modules = env('BROWSERSHOT_NODE_MODULE_PATH')) {
            $shot->setNodeModulePath($modules);
        }
        if ($chrome = env('BROWSERSHOT_CHROME_PATH')) {
            $shot->setChromePath($chrome);
        }

        // Docker sandbox — chromium refuses to run as root without --no-sandbox
        $shot->noSandbox();

        return $shot->pdf();
    }

    public function filename(InjectorProtocol $protocol): string
    {
        $num = $protocol->protocol_number ?: ('protocol-' . $protocol->id);
        return $num . '.pdf';
    }
}
