<?php

declare(strict_types=1);

final class NotificationEmailsService
{
    public function __construct(
        private readonly NotificationEmailsRepository $repository,
        private readonly MicFormRepository $forms,
        private readonly MyronMailSettingsRepository $mailSettings,
    ) {
    }

    public function list(bool $verifiedOnly = false): array
    {
        return ['notificationEmails' => $this->repository->listAll($verifiedOnly)];
    }

    public function create(array $input, MyronActionCallerContext $caller): array
    {
        $record = $this->repository->create((string) ($input['label'] ?? ''), (string) ($input['address'] ?? ''), $caller->callerId);
        $this->sendVerification($record);
        unset($record['_token']);
        return ['notificationEmail' => $record];
    }

    public function resendVerification(string $id): array
    {
        $record = $this->repository->rotateToken($id);
        $this->sendVerification($record);
        unset($record['_token']);
        return ['notificationEmail' => $record];
    }

    public function delete(string $id): array
    {
        $this->repository->delete($id, $this->forms);
        return ['deleted' => true];
    }

    public function setDefault(string $id): array
    {
        $this->repository->setDefault($id);
        return ['defaultNotificationEmailId' => $id];
    }

    public function verify(string $id, string $token): bool
    {
        return $this->repository->verify($id, $token);
    }

    private function sendVerification(array $record): void
    {
        $settings = $this->mailSettings->getSettings();
        if (!is_array($settings)) {
            return;
        }
        $token = (string) ($record['_token'] ?? '');
        $link = myronBuildPublicRouteUrl('/verify-notification-email', ['ne_id' => (string) $record['id'], 'token' => $token]);
        if (!str_starts_with($link, 'http')) {
            $link = rtrim(myronAppUrl(), '/') . $link;
        }
        $subject = 'Verify your destination email for ' . myronSiteTitle();
        $html = '<p>Verify this destination email address for ' . myronEscape(myronSiteTitle()) . '.</p>'
            . '<p><a href="' . myronEscape($link) . '">Verify destination email</a></p>'
            . '<p>This link expires in 24 hours.</p>';
        $text = "Verify this destination email address for " . myronSiteTitle() . ".\n\n{$link}\n\nThis link expires in 24 hours.";
        $envelope = new MailEnvelope(
            to: (string) $record['address'],
            subject: $subject,
            htmlBody: $html,
            textBody: $text,
            fromEmail: (string) ($settings['from_email'] ?? ''),
            fromName: (string) ($settings['from_name'] ?? 'MyronCMS'),
        );
        myronMailTransportRegistry()->activeTransport()->send($envelope);
    }
}
