<?php

namespace GriffinForms\Includes\Pipelines\Accounts;

class PasswordVault
{
    public function storeForAction(string $action_id, string $password, int $ttl = Contract::PASSWORD_VAULT_TTL): bool
    {
        $action_id = sanitize_key($action_id);
        if ($action_id === '' || $password === '') {
            return false;
        }

        return set_transient($this->buildKey($action_id), $password, max(60, $ttl));
    }

    public function retrieveForAction(string $action_id): string
    {
        $action_id = sanitize_key($action_id);
        if ($action_id === '') {
            return '';
        }

        $value = get_transient($this->buildKey($action_id));
        return is_string($value) ? $value : '';
    }

    public function deleteForAction(string $action_id): void
    {
        $action_id = sanitize_key($action_id);
        if ($action_id === '') {
            return;
        }

        delete_transient($this->buildKey($action_id));
    }

    private function buildKey(string $action_id): string
    {
        return Contract::PASSWORD_VAULT_KEY_PREFIX . $action_id;
    }
}
