<?php

declare(strict_types=1);

namespace apexl\Io\factories;

use apexl\Config\ConfigurationInterface;
use apexl\Config\Exceptions\MissingConfigException;
use DI\Container;
use DI\DependencyException;
use DI\NotFoundException;
use PHPMailer\PHPMailer\PHPMailer;

final readonly class PHPMailerFactory
{
    public function __construct(private Container $container, private ConfigurationInterface $configuration) {}

    /**
     * @throws MissingConfigException
     * @throws DependencyException
     * @throws NotFoundException
     */
    public function make(): PHPMailer
    {
        $mail = $this->container->make(PHPMailer::class, [
            'exceptions' => true,
        ]);

        //Allow config to set mailer settings.
        if (!!$this->configuration->get('smtp')) {
            $mail->isSMTP();
            $mail->Host = $this->configuration->get('smtp.host');
            $mail->SMTPAuth = $this->configuration->get('smtp.auth');
            $mail->Username = $this->configuration->get('smtp.username');
            $mail->Password = $this->configuration->get('smtp.password');
            $mail->SMTPSecure = $this->configuration->get('smtp.encryption');
            $mail->Port = $this->configuration->get('smtp.port');
            $mail->From = $this->configuration->get('smtp.from');
        }

        return $mail;
    }
}