<?php

namespace App\Domains\Unterschrift\Controllers;

use App\Domains\Unterschrift\Actions\SignDocument\SignDocumentCommand;
use App\Domains\Unterschrift\Actions\SignDocument\SignDocumentRequest;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use RuntimeException;

class SignController
{
    public function __invoke(Request $request): Response|JsonResponse
    {
        $request->validate([
            'pdf'             => 'required|file|mimetypes:application/pdf|max:20480',
            'signatur'        => 'required|file|mimetypes:image/png,image/jpeg,image/webp|max:8192',
            'page'            => 'required|integer|min:1',
            'xFrac'           => 'required|numeric|between:0,1',
            'yFrac'           => 'required|numeric|between:0,1',
            'widthFrac'       => 'required|numeric|between:0,1',
            'stempel'         => 'nullable|file|mimetypes:image/png,image/jpeg,image/webp|max:8192',
            'stempelXFrac'    => 'nullable|numeric|between:0,1',
            'stempelYFrac'    => 'nullable|numeric|between:0,1',
            'stempelWidthFrac' => 'nullable|numeric|between:0,1',
        ]);

        try {
            $signRequest = SignDocumentRequest::fromArray(
                $request->all(),
                $request->file('pdf')->getRealPath(),
                $request->file('signatur')->getRealPath(),
                $request->file('stempel')?->getRealPath(),
            );

            $result = (new SignDocumentCommand($signRequest))->execute();
        } catch (RuntimeException $e) {
            return response()->json(['message' => $e->getMessage()], 422);
        }

        return response($result->pdfContent, 200, [
            'Content-Type'        => 'application/pdf',
            'Content-Disposition' => 'inline; filename="' . $result->filename . '"',
        ]);
    }
}
