<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\Settings;

use Ferienpass\CoreBundle\Tenant\TenantContext;
use Symfony\Component\DependencyInjection\Attribute\Autowire;

class MailConfigManager
{
    public function __construct(
        private readonly PageConfigManager $pageConfigManager,
        private readonly TenantContext $tenantContext,
        #[Autowire(param: 'env(default::ADMIN_EMAIL)')]
        private readonly ?string $adminEmailEnv = null,
        #[Autowire(param: 'ferienpass.reply_address')]
        private readonly ?string $replyAddressConfig = null,
    ) {
    }

    /**
     * A build-wide sender address is fine for one municipality and wrong for
     * several, so on a multi-tenant installation the tenant's own PageConfig
     * wins over ADMIN_EMAIL. (The other per-municipality options are rejected
     * outright at build time; this one comes from the environment, which the
     * container cannot reliably inspect at compile time.).
     */
    public function isAdminEmailFromEnv(): bool
    {
        if ($this->tenantContext->isEnabled()) {
            return false;
        }

        return null !== $this->adminEmailEnv && '' !== $this->adminEmailEnv;
    }

    public function isReplyToFromConfig(): bool
    {
        return null !== $this->replyAddressConfig && '' !== $this->replyAddressConfig;
    }

    public function getAdminEmail(): ?string
    {
        if ($this->isAdminEmailFromEnv()) {
            return $this->adminEmailEnv;
        }

        return $this->pageConfigManager->getPageConfig()->getAdminEmail();
    }

    public function getAdminEmailName(): ?string
    {
        return $this->pageConfigManager->getPageConfig()->getAdminEmailName();
    }

    public function getReplyTo(): ?string
    {
        if (null !== $this->replyAddressConfig && '' !== $this->replyAddressConfig) {
            return $this->replyAddressConfig;
        }

        return $this->pageConfigManager->getPageConfig()->getReplyToEmail();
    }

    public function getReplyToName(): ?string
    {
        return $this->pageConfigManager->getPageConfig()->getReplyToName();
    }
}
