<?php

namespace App\Services;

use Illuminate\Support\Facades\Storage;

class TerritorioThumbnailService
{
    /**
     * Generate a PNG thumbnail of the first page of a PDF stored on the public disk.
     *
     * @param  string  $pdfStoragePath  Relative path within the public disk (e.g. "territori-pdf/abc.pdf")
     * @return string|null  Relative path of the saved thumbnail, or null on failure
     */
    public function generate(string $pdfStoragePath): ?string
    {
        $pdfAbsPath = Storage::disk('public')->path($pdfStoragePath);

        if (!file_exists($pdfAbsPath)) {
            return null;
        }

        $tempPrefix = sys_get_temp_dir() . '/terr_thumb_' . uniqid();

        exec(
            'pdftoppm -r 72 -png -l 1 ' . escapeshellarg($pdfAbsPath) . ' ' . escapeshellarg($tempPrefix),
            $output,
            $exitCode
        );

        // pdftoppm may produce -1.png, -01.png or even -001.png depending on page count
        $generated = null;
        foreach (['-1.png', '-01.png', '-001.png'] as $suffix) {
            $candidate = $tempPrefix . $suffix;
            if (file_exists($candidate)) {
                $generated = $candidate;
                break;
            }
        }

        if (!$generated) {
            return null;
        }

        $thumbRelPath = 'territori-thumbnails/' . basename($pdfStoragePath, '.pdf') . '.png';
        Storage::disk('public')->put($thumbRelPath, file_get_contents($generated));
        unlink($generated);

        return $thumbRelPath;
    }

    /**
     * Delete an existing thumbnail from the public disk.
     */
    public function delete(string $thumbnailPath): void
    {
        if ($thumbnailPath) {
            Storage::disk('public')->delete($thumbnailPath);
        }
    }
}
