<?php

namespace App\Domains\Unterschrift\Controllers;

use App\Domains\Unterschrift\Actions\RenderPreview\RenderPreviewCommand;
use App\Domains\Unterschrift\Actions\RenderPreview\RenderPreviewRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use RuntimeException;

class PreviewPageController
{
    public function __invoke(Request $request): JsonResponse
    {
        $request->validate([
            'pdf' => 'required|file|mimetypes:application/pdf|max:20480',
        ]);

        try {
            $command  = new RenderPreviewCommand(
                new RenderPreviewRequest($request->file('pdf')->getRealPath())
            );
            $response = $command->execute();
        } catch (RuntimeException $e) {
            return response()->json(['message' => $e->getMessage()], 422);
        }

        return response()->json([
            'pages'     => $response->pages,
            'pageCount' => $response->pageCount,
        ]);
    }
}
