<?php

namespace App\Core\Dns;

abstract class AbstractDnsDriver implements DnsDriverInterface
{
    protected array $config;

    public function __construct(array $config = [])
    {
        $this->config = $config;
    }

    protected function getConfig(string $key, $default = null)
    {
        return $this->config[$key] ?? $default;
    }

    public function requiresApiKey(): bool
    {
        return true;
    }

    public function adminFields(): array
    {
        return $this->requiresApiKey()
            ? ['api_key' => ['type' => 'password', 'label' => 'API Key', 'required' => true]]
            : [];
    }

    public function testConnection(): array
    {
        try {
            // Subclasses override; default just checks credentials presence.
            $required = array_filter($this->adminFields(), fn ($f) => ! empty($f['required']));
            foreach (array_keys($required) as $key) {
                if (empty($this->getConfig($key))) {
                    return ['success' => false, 'message' => "Missing required config: {$key}"];
                }
            }

            return ['success' => true, 'message' => 'Configuration looks valid (live test in subclass)'];
        } catch (\Throwable $e) {
            return ['success' => false, 'message' => $e->getMessage()];
        }
    }
}
