<?php
namespace EasyChat\Library\Messenger\Marketplace;

use EasyChat\Library\Messenger\SecretBox;
use EasyChat\Model\Setting;

 
class MarketplaceCredentialsVault {
    private $registry;

    public function __construct($registry) {
        $this->registry = $registry;
    }

    public function seal(array $credentials, array $secret_fields): array {
        $secret = $this->installSecret();
        if ($secret === '') {
            throw new \RuntimeException('install_secret_missing');
        }
        foreach ($secret_fields as $field) {
            if (array_key_exists($field, $credentials) && trim((string)$credentials[$field]) !== '') {
                $credentials[$field] = SecretBox::encrypt((string)$credentials[$field], $secret);
            }
        }
        return $credentials;
    }

    public function open(array $credentials, array $secret_fields): array {
        $secret = $this->installSecret();
        foreach ($secret_fields as $field) {
            $stored = trim((string)($credentials[$field] ?? ''));
            if ($stored === '') {
                $credentials[$field] = '';
                continue;
            }
            $credentials[$field] = strpos($stored, 'enc:v1:') === 0 && $secret !== ''
                ? SecretBox::decrypt($stored, $secret)
                : '';
        }
        return $credentials;
    }

    public function mask(array $credentials, array $secret_fields): array {
        $opened = $this->open($credentials, $secret_fields);
        $masked = [];
        foreach ($secret_fields as $field) {
            $masked[$field] = SecretBox::mask((string)($opened[$field] ?? ''));
        }
        return $masked;
    }

    public function sealThreadSecret(string $plain): string {
        $secret = $this->installSecret();
        return $plain !== '' && $secret !== '' ? SecretBox::encrypt($plain, $secret) : '';
    }

    public function openThreadSecret(string $stored): string {
        $secret = $this->installSecret();
        return $stored !== '' && $secret !== '' ? SecretBox::decrypt($stored, $secret) : '';
    }

    private function installSecret(): string {
        return (string)(new Setting($this->registry))->get('chat_install_secret', '');
    }
}
