<?php

namespace WPSN\Modules\AI;

use WPSN\Core\Secrets\EncryptedOption;

defined('ABSPATH') || exit;

/**
 * Stores secrets separately from main settings so they are NOT exported.
 */
final class AISecretsRepository
{
    public const OPTION_NAME = 'wpsn_ai_secrets';

    /**
     * @return array<string, mixed>
     */
    public function getAll(): array
    {
        return EncryptedOption::getArray(self::OPTION_NAME);
    }

    public function getOpenAIKey(): string
    {
        $all = $this->getAll();
        $key = isset($all['openai_api_key']) ? (string) $all['openai_api_key'] : '';
        return trim($key);
    }

    public function hasOpenAIKey(): bool
    {
        return $this->getOpenAIKey() !== '';
    }

    public function setOpenAIKey(string $key): void
    {
        $key = trim($key);
        $all = $this->getAll();
        $all['openai_api_key'] = $key;
        EncryptedOption::updateArray(self::OPTION_NAME, $all);
    }

    public function clearOpenAIKey(): void
    {
        $all = $this->getAll();
        unset($all['openai_api_key']);
        EncryptedOption::updateArray(self::OPTION_NAME, $all);
    }
}
