<?php

declare(strict_types=1);

namespace Maestro\Core\Modules\Offers\Services;

use Illuminate\Support\Facades\Storage;
use InvalidArgumentException;

final class OfferSignatureStorage
{
    private const MAX_BYTES = 2_000_000;

    public static function storeFromBase64Png(string $base64, string $publicUuid): string
    {
        $raw = base64_decode($base64, true);
        if ($raw === false || $raw === '') {
            throw new InvalidArgumentException('Invalid signature payload.');
        }

        if (strlen($raw) > self::MAX_BYTES) {
            throw new InvalidArgumentException('Signature too large.');
        }

        if (strlen($raw) < 8 || substr($raw, 0, 8) !== "\x89PNG\r\n\x1a\n") {
            throw new InvalidArgumentException('Signature must be a PNG image.');
        }

        $relative = 'offer-signatures/'.$publicUuid.'.png';
        Storage::disk('public')->put($relative, $raw);

        return $relative;
    }
}
