<?php

namespace CaptureRelay;

use RuntimeException;

final class CredentialVault
{
    public static function seal(string $plaintext): string
    {
        $iv = random_bytes(12);
        $tag = '';
        $ciphertext = openssl_encrypt(
            $plaintext,
            'aes-256-gcm',
            self::key(),
            OPENSSL_RAW_DATA,
            $iv,
            $tag,
            'capture-relay-device-credential',
            16
        );
        if ($ciphertext === false) {
            throw new RuntimeException('Unable to protect device credential.');
        }
        return base64_encode($iv . $tag . $ciphertext);
    }

    public static function open(string $envelope): string
    {
        $raw = base64_decode($envelope, true);
        if ($raw === false || strlen($raw) < 29) {
            throw new RuntimeException('Invalid protected credential.');
        }
        $iv = substr($raw, 0, 12);
        $tag = substr($raw, 12, 16);
        $ciphertext = substr($raw, 28);
        foreach (self::candidateKeys() as $key) {
            $plaintext = openssl_decrypt(
                $ciphertext,
                'aes-256-gcm',
                $key,
                OPENSSL_RAW_DATA,
                $iv,
                $tag,
                'capture-relay-device-credential'
            );
            if ($plaintext !== false) {
                return $plaintext;
            }
        }
        throw new RuntimeException('Unable to open protected credential.');
    }

    private static function key(): string
    {
        $material = (defined('AUTH_KEY') ? AUTH_KEY : '') . '|' . (defined('SECURE_AUTH_KEY') ? SECURE_AUTH_KEY : '');
        if ($material === '|') {
            $material = wp_salt('auth') . '|' . wp_salt('secure_auth');
        }
        return hash_hkdf('sha256', $material, 32, 'capture-relay-at-rest-v1', Security::siteIdentity());
    }

    private static function candidateKeys(): array
    {
        $keys = [self::key()];
        $material = (defined('AUTH_KEY') ? AUTH_KEY : '') . '|' . (defined('SECURE_AUTH_KEY') ? SECURE_AUTH_KEY : '');
        if ($material === '|') {
            $material = wp_salt('auth') . '|' . wp_salt('secure_auth');
        }
        foreach ([home_url('/', 'http'), home_url('/', 'https')] as $legacySiteUrl) {
            $keys[] = hash_hkdf('sha256', $material, 32, 'capture-relay-at-rest-v1', $legacySiteUrl);
        }
        return array_values(array_unique($keys));
    }
}
