<?php

namespace App\Services;

use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Support\Facades\Crypt;

class InvoiceTokenService
{
    public function encryptOrderId(int $orderId): string
    {
        $encrypted = Crypt::encryptString((string) $orderId);

        return rtrim(strtr(base64_encode($encrypted), '+/', '-_'), '=');
    }

    /**
     * @throws DecryptException
     */
    public function decryptOrderId(string $token): int
    {
        $padded = strtr($token, '-_', '+/');
        $padding = strlen($padded) % 4;
        if ($padding > 0) {
            $padded .= str_repeat('=', 4 - $padding);
        }

        $decoded = base64_decode($padded, true);
        if ($decoded === false) {
            throw new DecryptException('Invalid invoice token encoding.');
        }

        $orderId = (int) Crypt::decryptString($decoded);
        if ($orderId <= 0) {
            throw new DecryptException('Invalid invoice token payload.');
        }

        return $orderId;
    }
}
