<?php

namespace App\Base\Config;

use Symfony\Component\DependencyInjection\Attribute\Autowire;

class SmtpConfig implements ConfigInterface
{
    private array $messages = [];

    /*
     * SMTP is considered enabled if any of
     * the parameters are set. If none are set,
     * then the User must not need it.
     */
    private bool $isEnabled = false;

    public function __construct(
        #[Autowire(env: 'SMTP_HOST')]
        private readonly ?string $smtpHost,
        #[Autowire(env: 'SMTP_USER')]
        private readonly ?string $smtpUser,
        #[Autowire(env: 'SMTP_PASS')]
        private readonly ?string $smtpPass,
        #[Autowire(env: 'SMTP_PORT')]
        private readonly ?string $smtpPort,
        #[Autowire(env: 'SMTP_FROM')]
        private readonly ?string $smtpFrom,
        #[Autowire(env: 'SMTP_FROM_NAME')]
        private readonly ?string $smtpFromName,
    ) {
        foreach (func_get_args() as $key => $value) {
            if ("" !== $value && $value !== null) {
                $this->isEnabled = true;
            }
        }
    }

    public function isEnabled(): bool
    {
        return $this->isEnabled;
    }

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

    public function isValid(): bool
    {
        if (false === $this->isEnabled) {
            return true;
        }

        $valid = true;

        $params = [
            'SMTP_HOST' => $this->smtpHost,
            'SMTP_USER' => $this->smtpUser,
            'SMTP_PASS' => $this->smtpPass,
            'SMTP_PORT' => $this->smtpPort,
            'SMTP_FROM' => $this->smtpFrom,
            'SMTP_FROM_NAME' => $this->smtpFromName,
        ];

        foreach ($params as $key => $value) {
            if (false === $this->isVariableValid($key, $value)) {
                $valid = false;
            }
        }

        return $valid;
    }

    private function isVariableValid($key, $value): bool
    {
        if ("" === $value || null === $value) {
            $this->messages[] = "Your SMTP is misconfigured. Please set the $key environment variable appropriately.";
            return false;
        }
        return true;
    }

    public function getSmtpHost(): ?string
    {
        return $this->smtpHost;
    }

    public function getSmtpUser(): ?string
    {
        return $this->smtpUser;
    }

    public function getSmtpPass(): ?string
    {
        return $this->smtpPass;
    }

    public function getSmtpPort(): ?string
    {
        return $this->smtpPort;
    }

    public function getSmtpFrom(): ?string
    {
        return $this->smtpFrom;
    }

    public function getSmtpFromName(): ?string
    {
        return $this->smtpFromName;
    }
}
