<?php

namespace App\Support;

/**
 * Normalizes VAPID material from .env for minishlink/web-push (expects Base64URL).
 */
final class VapidConfig
{
    public static function subject(?string $raw): string
    {
        $s = trim((string) $raw);
        if ($s === '') {
            return 'mailto:support@example.com';
        }

        if (str_starts_with($s, 'mailto:') || str_starts_with($s, 'https://') || str_starts_with($s, 'http://')) {
            return $s;
        }

        return 'mailto:'.$s;
    }

    public static function publicKey(?string $raw): string
    {
        return self::toBase64Url((string) $raw);
    }

    public static function privateKey(?string $raw): string
    {
        return self::toBase64Url((string) $raw);
    }

    private static function toBase64Url(string $value): string
    {
        $value = trim($value);
        $value = str_replace(["\r", "\n", ' '], '', $value);

        if ($value === '') {
            return '';
        }

        // Many generators emit standard Base64 (+ / with padding). WebPush expects Base64URL.
        if (str_contains($value, '+') || str_contains($value, '/')) {
            $value = strtr($value, '+/', '-_');
        }

        return rtrim($value, '=');
    }
}
