<?php

namespace App\Base;

use App\Base\Config\AppConfig;
use App\Base\Config\AuthConfig;
use App\Base\Config\SmtpConfig;
use Psr\Log\LoggerInterface;
use Symfony\Contracts\Cache\TagAwareCacheInterface;

final class ConfigResolver
{
    private array $messages = [];

    public function __construct(
        private readonly LoggerInterface $logger,
        private readonly TagAwareCacheInterface $cache,
        private readonly AuthConfig $authConfig,
        private readonly SmtpConfig $smtpConfig,
        private readonly AppConfig $appConfig,
    ) {}

    public function validate(): bool
    {
        if ("prod" === strtolower($this->appConfig->getAppEnv())) {
            return $this->cache->get('app.valid_config', function () {
                return $this->doValidate();
            });
        } else {
            return $this->doValidate();
        }
    }

    private function doValidate(): bool
    {
        $valid = true;

        if (false === $this->appConfig->isValid()) {
            $this->messages += $this->appConfig->getMessages();
            $valid = false;
        }

        if (false === $this->authConfig->isValid()) {
            $this->messages += $this->authConfig->getMessages();
            $valid = false;
        }

        if (false === $this->smtpConfig->isValid()) {
            $this->messages += $this->smtpConfig->getMessages();
            $valid = false;
        }

        if (false === $valid) {
            foreach ($this->messages as $message) {
                $this->logger->error('> [ConfigResolver] ' . $message);
            }
        }

        return $valid;
    }

    public function getMessages(): array
    {
        return $this->messages;
    }

    public function getAuthConfig(): AuthConfig
    {
        return $this->authConfig;
    }

    public function authIs(string $method): bool
    {
        return $this->authConfig->isMethod($method);
    }

    public function getAuthMethod(): string
    {
        return $this->authConfig->getAuthMethod();
    }
}
