<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\services;

use apexl\Config\ConfigurationInterface;
use apexl\Io\factories\MailerFactory;
use apexl\Io\modules\template\Services\TemplateService;
use apexl\Io\modules\user\exceptions\ForgotPasswordEmailException;
use apexl\Io\services\Mailer;
use app\vendor\apexl\utils\src\Utils\Strings\Append;
use PHPMailer\PHPMailer\Exception as MailerException;

final readonly class ForgotPasswordEmailFactory
{
    public function __construct(
        private ConfigurationInterface $config,
        private MailerFactory $mailerFactory,
        private TemplateService $templateService
    ) {}

    /**
     * @throws ForgotPasswordEmailException
     */
    public function create(string $firstName, string $email, string $link): Mailer
    {
        /**
         * @TODO Allow for database config here.
         */
        $from = $this->config->get('app.site.email_address') ?? 'no-reply@localhost.com';
        $fromName = $this->config->get('app.site.name') ?? 'localhost';
        $frontEndDomain = $this->config->get('app.site.frontend_domain') ?? 'localhost';

        $link = Append::append($frontEndDomain, $link);

        try {
            $mailer = $this->mailerFactory->make();
            $mailer->setFrom($from, $fromName);
            $mailer->addAddress($email, $firstName);     // Add a recipient

            $mailer->Subject = 'Password Reset Request';
            $mailer->Body = $this->templateService->template('email/password_reset', [
                'from_name' => $fromName,
                'reset_link' => $link,
                'name' => $firstName,
            ]);
            $mailer->IsHTML();

            return $mailer;
        } catch (MailerException $e) {
            throw new ForgotPasswordEmailException(
                sprintf('Unable to send forgot password email: %s', $e->getMessage()),
                E_USER_WARNING
            );
        }
    }

}