<?php

declare(strict_types=1);

namespace apexl\Io\modules\user\services;

use apexl\Io\factories\MailerFactory;
use apexl\Io\modules\email\services\TemplateService;
use apexl\Io\modules\user\exceptions\ForgotPasswordEmailException;
use apexl\Io\services\Mailer;
use PHPMailer\PHPMailer\Exception as MailerException;

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

    /**
     * @throws ForgotPasswordEmailException
     */
    public function create(string $firstName, string $email, string $link): Mailer
    {
        /**
         * @TODO Allow for database config here.
         * @TODO Move all this to the central mailer system, make an easy to use mailer function
         */
        $from = config('app.site.email_address') ?? 'no-reply@localhost.com';
        $fromName = config('app.site.name') ?? 'localhost';
        $frontEndDomain = config('app.site.frontend_domain') ?? 'localhost';

        /** @TODO Move to config. * */
        //$link = rtrim((string) $frontEndDomain, '/').'/api/v1/user/data/forgot-password/h/'.$string;
        $link = rtrim($frontEndDomain, '/') . '/' . ltrim('/' . $link, '/');

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

            $mailer->Subject = 'Password Reset Request';
            $mailer->Body = $this->templateService->fetch('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
            );
        }
    }

}