<?php

/** AES-256-GCM helpers for the TOTP secret at rest. */
final class Crypto
{
    private static function key(): string
    {
        $hex = (string) Config::get('app_key');
        if (strlen($hex) !== 64 || !ctype_xdigit($hex)) {
            throw new RuntimeException('app_key must be 64 hex characters. Run: php bin/genkey.php');
        }
        return hex2bin($hex);
    }

    /** @return array{0:string,1:string,2:string} ciphertext, iv, tag */
    public static function encrypt(string $plain): array
    {
        $iv  = random_bytes(12);
        $tag = '';
        $ct  = openssl_encrypt($plain, 'aes-256-gcm', self::key(), OPENSSL_RAW_DATA, $iv, $tag);
        if ($ct === false) {
            throw new RuntimeException('Encryption failed');
        }
        return [$ct, $iv, $tag];
    }

    public static function decrypt(string $ct, string $iv, string $tag): string
    {
        $plain = openssl_decrypt($ct, 'aes-256-gcm', self::key(), OPENSSL_RAW_DATA, $iv, $tag);
        if ($plain === false) {
            throw new RuntimeException('Decryption failed');
        }
        return $plain;
    }
}
