<?php

namespace App\Domains\Unterschrift\Actions\SignDocument;

class SignDocumentRequest
{
    public function __construct(
        public readonly string $pdfPath,
        public readonly string $signaturPath,
        public readonly int $page,
        public readonly float $xFrac,
        public readonly float $yFrac,
        public readonly float $widthFrac,
        public readonly bool $graustufen,
        public readonly string $filename,
        public readonly ?string $stempelPath = null,
        public readonly float $stempelXFrac = 0.0,
        public readonly float $stempelYFrac = 0.0,
        public readonly float $stempelWidthFrac = 0.18,
    ) {}

    public static function fromArray(array $data, string $pdfPath, string $signaturPath, ?string $stempelPath = null): self
    {
        return new self(
            pdfPath:          $pdfPath,
            signaturPath:     $signaturPath,
            page:             max(1, (int) ($data['page'] ?? 1)),
            xFrac:            self::clamp((float) ($data['xFrac'] ?? 0)),
            yFrac:            self::clamp((float) ($data['yFrac'] ?? 0)),
            widthFrac:        self::clamp((float) ($data['widthFrac'] ?? 0.2), 0.02, 1.0),
            graustufen:       filter_var($data['graustufen'] ?? true, FILTER_VALIDATE_BOOLEAN),
            filename:         'signiert.pdf',
            stempelPath:      $stempelPath,
            stempelXFrac:     self::clamp((float) ($data['stempelXFrac'] ?? 0)),
            stempelYFrac:     self::clamp((float) ($data['stempelYFrac'] ?? 0)),
            stempelWidthFrac: self::clamp((float) ($data['stempelWidthFrac'] ?? 0.18), 0.02, 1.0),
        );
    }

    private static function clamp(float $value, float $min = 0.0, float $max = 1.0): float
    {
        return max($min, min($max, $value));
    }
}
