<?php
declare(strict_types=1);
namespace App\Mailer;

use App\Settings\SettingsRepository;

final class MailerFactory
{
    public function __construct(private readonly SettingsRepository $settings, private readonly string $fallbackSiteName = 'Quaeriva') {}
    public function make(): MailerInterface
    {
        if (!(bool)$this->settings->get('mail.enabled', false)) return new NullMailer();
        $fromEmail=trim((string)$this->settings->get('mail.from_email',''));
        $fromName=trim((string)$this->settings->get('mail.from_name',(string)$this->settings->get('site.name',$this->fallbackSiteName)));
        if($fromName==='')$fromName=$this->fallbackSiteName;
        $transport=strtolower(trim((string)$this->settings->get('mail.transport','mail')));
        if($transport==='smtp') return new SmtpMailer(
            trim((string)$this->settings->get('mail.smtp.host','')),
            max(1,(int)$this->settings->get('mail.smtp.port',587)),
            strtolower(trim((string)$this->settings->get('mail.smtp.encryption','starttls'))),
            trim((string)$this->settings->get('mail.smtp.username','')),
            (string)$this->settings->get('mail.smtp.password',''),
            strtolower(trim((string)$this->settings->get('mail.smtp.auth','login'))),
            $fromEmail,$fromName
        );
        return new PhpMailMailer($fromEmail,$fromName);
    }
}
