function Write-ProjectFile {
    param(
        [Parameter(Mandatory = $true)][string]$Path,
        [Parameter(Mandatory = $true)][string]$Content
    )

    $directory = Split-Path -Parent $Path
    if ($directory) {
        New-Item -ItemType Directory -Force -Path $directory | Out-Null
    }

    Set-Content -LiteralPath $Path -Value $Content -NoNewline
}

Write-ProjectFile 'app/Services/Templates/TemplateVariableCatalog.php' @'
<?php

namespace App\Services\Templates;

use App\Enums\ResponseTemplateCategory;
use App\Enums\ResponseTemplateChannel;

class TemplateVariableCatalog
{
    public static function channels(): array
    {
        return array_map(
            fn (ResponseTemplateChannel $channel): array => [
                'value' => $channel->value,
                'label' => $channel->label(),
            ],
            ResponseTemplateChannel::cases(),
        );
    }

    public static function categories(): array
    {
        return array_map(
            fn (ResponseTemplateCategory $category): array => [
                'value' => $category->value,
                'label' => $category->label(),
            ],
            ResponseTemplateCategory::cases(),
        );
    }

    public static function definitions(): array
    {
        return [
            'name' => ['label' => 'Name', 'description' => 'Contact person name.', 'categories' => ['lead_received', 'follow_up', 'custom']],
            'email' => ['label' => 'Email', 'description' => 'Contact email address.', 'categories' => ['lead_received', 'follow_up', 'custom']],
            'company' => ['label' => 'Company', 'description' => 'Company name from the inquiry.', 'categories' => ['lead_received', 'follow_up', 'custom']],
            'phone' => ['label' => 'Phone', 'description' => 'Phone number from the inquiry.', 'categories' => ['lead_received', 'follow_up', 'custom']],
            'subject' => ['label' => 'Subject', 'description' => 'Inquiry subject line.', 'categories' => ['lead_received', 'follow_up', 'custom']],
            'message' => ['label' => 'Message', 'description' => 'Full inquiry message.', 'categories' => ['lead_received', 'follow_up', 'custom']],
            'message_preview' => ['label' => 'Message Preview', 'description' => 'Shortened version of the inquiry body.', 'categories' => ['lead_received', 'follow_up', 'custom']],
            'source_page' => ['label' => 'Source Page', 'description' => 'Landing page or URL where the message was submitted.', 'categories' => ['lead_received', 'follow_up', 'custom']],
            'created_at' => ['label' => 'Created At', 'description' => 'Timestamp of the source event.', 'categories' => ['lead_received', 'follow_up', 'article_published', 'system_alert', 'custom']],
            'admin_reference' => ['label' => 'Admin Reference', 'description' => 'Admin-side identifier or reference string.', 'categories' => ['lead_received', 'follow_up', 'article_published', 'system_alert', 'custom']],
            'article_title' => ['label' => 'Article Title', 'description' => 'Published article title.', 'categories' => ['article_published', 'custom']],
            'article_slug' => ['label' => 'Article Slug', 'description' => 'Published article slug.', 'categories' => ['article_published', 'custom']],
            'published_at' => ['label' => 'Published At', 'description' => 'Article publication timestamp.', 'categories' => ['article_published', 'custom']],
            'environment' => ['label' => 'Environment', 'description' => 'Deployment or build environment.', 'categories' => ['system_alert', 'custom']],
            'status' => ['label' => 'Status', 'description' => 'Operational status of the alert source.', 'categories' => ['system_alert', 'custom']],
            'error_message' => ['label' => 'Error Message', 'description' => 'Error details for failed operational events.', 'categories' => ['system_alert', 'custom']],
            'started_at' => ['label' => 'Started At', 'description' => 'Start time for an operational event.', 'categories' => ['system_alert', 'custom']],
            'finished_at' => ['label' => 'Finished At', 'description' => 'Finish time for an operational event.', 'categories' => ['system_alert', 'custom']],
            'alert_title' => ['label' => 'Alert Title', 'description' => 'Headline for a system alert.', 'categories' => ['system_alert', 'custom']],
            'alert_message' => ['label' => 'Alert Message', 'description' => 'Body text for a system alert.', 'categories' => ['system_alert', 'custom']],
            'occurred_at' => ['label' => 'Occurred At', 'description' => 'When the critical event happened.', 'categories' => ['system_alert', 'custom']],
            'context_json' => ['label' => 'Context JSON', 'description' => 'Serialized structured context for alerts.', 'categories' => ['system_alert', 'custom']],
        ];
    }

    public static function variableNames(): array
    {
        return array_keys(self::definitions());
    }

    public static function allowedForCategory(ResponseTemplateCategory|string|null $category): array
    {
        $categoryValue = $category instanceof ResponseTemplateCategory
            ? $category->value
            : ($category ?? ResponseTemplateCategory::CUSTOM->value);

        if ($categoryValue === ResponseTemplateCategory::CUSTOM->value) {
            return self::variableNames();
        }

        return collect(self::definitions())
            ->filter(fn (array $definition): bool => in_array($categoryValue, $definition['categories'], true))
            ->keys()
            ->values()
            ->all();
    }

    public static function sampleData(ResponseTemplateCategory|string|null $category): array
    {
        $categoryValue = $category instanceof ResponseTemplateCategory
            ? $category->value
            : ($category ?? ResponseTemplateCategory::CUSTOM->value);

        return match ($categoryValue) {
            ResponseTemplateCategory::LEAD_RECEIVED->value, ResponseTemplateCategory::FOLLOW_UP->value => [
                'name' => 'Alex Morgan',
                'email' => 'alex@example.com',
                'company' => 'Northwind Labs',
                'phone' => '+49 30 555 0101',
                'subject' => 'Website redesign inquiry',
                'message' => 'We would like to discuss a redesign and new content workflow.',
                'message_preview' => 'We would like to discuss a redesign and new content workflow.',
                'source_page' => 'https://itcarrot.com/contact',
                'created_at' => '2026-04-03 14:20:00',
                'admin_reference' => 'Message #42',
            ],
            ResponseTemplateCategory::ARTICLE_PUBLISHED->value => [
                'article_title' => 'How Itcarrot structures modern content operations',
                'article_slug' => 'how-itcarrot-structures-modern-content-operations',
                'published_at' => '2026-04-03 15:30:00',
                'created_at' => '2026-04-03 15:30:00',
                'admin_reference' => 'Article #12',
            ],
            ResponseTemplateCategory::SYSTEM_ALERT->value => [
                'environment' => 'production',
                'status' => 'failed',
                'error_message' => 'Astro build failed during static generation.',
                'started_at' => '2026-04-03 16:00:00',
                'finished_at' => '2026-04-03 16:02:12',
                'alert_title' => 'Critical service degradation',
                'alert_message' => 'The deployment pipeline reported a blocking failure.',
                'occurred_at' => '2026-04-03 16:02:12',
                'context_json' => '{"service":"astro-build","severity":"critical"}',
                'created_at' => '2026-04-03 16:02:12',
                'admin_reference' => 'Build #8',
            ],
            default => [
                'name' => 'Alex Morgan',
                'email' => 'alex@example.com',
                'company' => 'Northwind Labs',
                'phone' => '+49 30 555 0101',
                'subject' => 'General inquiry',
                'message' => 'This is sample content used for template previews.',
                'message_preview' => 'This is sample content used for template previews.',
                'source_page' => 'https://itcarrot.com/contact',
                'created_at' => '2026-04-03 14:20:00',
                'admin_reference' => 'Reference #1',
                'article_title' => 'Sample Article',
                'article_slug' => 'sample-article',
                'published_at' => '2026-04-03 15:30:00',
                'environment' => 'production',
                'status' => 'pending',
                'error_message' => 'Example failure message',
                'started_at' => '2026-04-03 16:00:00',
                'finished_at' => '2026-04-03 16:02:12',
                'alert_title' => 'Example alert',
                'alert_message' => 'Example alert body',
                'occurred_at' => '2026-04-03 16:02:12',
                'context_json' => '{"example":true}',
            ],
        };
    }
}
'@

Write-ProjectFile 'app/Services/Email/OutgoingEmailService.php' @'
<?php

namespace App\Services\Email;

use App\Enums\EmailLogStatus;
use App\Jobs\Email\SendFollowUpEmailJob;
use App\Jobs\Email\SendInquiryConfirmationJob;
use App\Mail\TemplatedBusinessMail;
use App\Models\EmailLog;
use App\Models\WebsiteMessage;
use App\Services\Logs\ActivityLogService;
use Illuminate\Support\Facades\Mail;
use Throwable;

class OutgoingEmailService
{
    public function __construct(
        private readonly EmailTemplateService $emailTemplates,
        private readonly ActivityLogService $activityLogs,
    ) {
    }

    public function queueInquiryConfirmation(WebsiteMessage $message): EmailLog
    {
        return $this->queueTemplatedEmail(
            EmailTemplateService::INQUIRY_CONFIRMATION_SLUG,
            $message->email,
            $this->emailTemplates->buildInquiryVariables($message),
            $message,
            ['flow' => 'inquiry_confirmation'],
            'inquiry_confirmation',
        );
    }

    public function queueFollowUpEmail(WebsiteMessage $message, string $templateSlug, array $variables = []): EmailLog
    {
        return $this->queueTemplatedEmail(
            $templateSlug,
            $message->email,
            array_merge($this->emailTemplates->buildInquiryVariables($message), $variables),
            $message,
            ['flow' => 'follow_up'],
            'follow_up',
        );
    }

    public function sendEmailLogById(int $logId): void
    {
        $log = EmailLog::query()->find($logId);

        if (! $log) {
            return;
        }

        $this->send($log);
    }

    public function markFailedById(int $logId, string $errorMessage): void
    {
        $log = EmailLog::query()->find($logId);

        if (! $log || $log->status === EmailLogStatus::SENT) {
            return;
        }

        $log->forceFill([
            'status' => EmailLogStatus::FAILED,
            'error_message' => $errorMessage,
        ])->save();
    }

    public function isConfigured(): bool
    {
        return filled(config('mail.default')) && filled(config('mail.from.address'));
    }

    private function queueTemplatedEmail(
        string $templateSlug,
        string $toEmail,
        array $variables,
        ?WebsiteMessage $websiteMessage,
        array $meta,
        string $flow,
    ): EmailLog {
        $log = null;

        try {
            if (! $this->isConfigured()) {
                return $this->createFailedLog(
                    $templateSlug,
                    $toEmail,
                    $websiteMessage,
                    'Email integration is not configured.',
                    $meta,
                );
            }

            $template = $this->emailTemplates->resolveActiveBySlug($templateSlug);
            $rendered = $this->emailTemplates->render($template, $variables);

            $log = EmailLog::query()->create([
                'website_message_id' => $websiteMessage?->getKey(),
                'template_id' => $template->getKey(),
                'to_email' => $toEmail,
                'subject' => $rendered['subject'],
                'rendered_body' => $rendered['body'],
                'status' => EmailLogStatus::PENDING,
                'provider' => (string) config('mail.default', 'mail'),
                'meta_json' => array_merge($meta, [
                    'template_slug' => $templateSlug,
                ]),
            ]);

            match ($flow) {
                'follow_up' => SendFollowUpEmailJob::dispatch($log->id),
                default => SendInquiryConfirmationJob::dispatch($log->id),
            };

            return $log;
        } catch (Throwable $exception) {
            report($exception);

            if ($log instanceof EmailLog) {
                $log->forceFill([
                    'status' => EmailLogStatus::FAILED,
                    'error_message' => $exception->getMessage(),
                ])->save();

                return $log;
            }

            return $this->createFailedLog(
                $templateSlug,
                $toEmail,
                $websiteMessage,
                $exception->getMessage(),
                $meta,
            );
        }
    }

    private function send(EmailLog $log): EmailLog
    {
        $log->forceFill([
            'status' => EmailLogStatus::PENDING,
            'error_message' => null,
        ])->save();

        try {
            Mail::to($log->to_email)->send(
                new TemplatedBusinessMail($log->subject, $log->rendered_body),
            );

            $log->forceFill([
                'status' => EmailLogStatus::SENT,
                'sent_at' => now(),
                'error_message' => null,
            ])->save();

            $this->activityLogs->record(
                'email.sent',
                'Outgoing email delivered successfully.',
                null,
                request(),
                $log->websiteMessage,
                ['email_log_id' => $log->id],
            );

            return $log;
        } catch (Throwable $exception) {
            $log->forceFill([
                'status' => EmailLogStatus::FAILED,
                'error_message' => $exception->getMessage(),
            ])->save();

            $this->activityLogs->record(
                'email.failed',
                'Outgoing email failed to send.',
                null,
                request(),
                $log->websiteMessage,
                ['email_log_id' => $log->id],
            );

            throw $exception;
        }
    }

    private function createFailedLog(
        string $templateSlug,
        string $toEmail,
        ?WebsiteMessage $websiteMessage,
        string $errorMessage,
        array $meta,
    ): EmailLog {
        return EmailLog::query()->create([
            'website_message_id' => $websiteMessage?->getKey(),
            'template_id' => null,
            'to_email' => $toEmail,
            'subject' => 'Unavailable template: '.$templateSlug,
            'rendered_body' => 'Email could not be prepared for delivery.',
            'status' => EmailLogStatus::FAILED,
            'provider' => (string) config('mail.default', 'mail'),
            'error_message' => $errorMessage,
            'meta_json' => array_merge($meta, [
                'template_slug' => $templateSlug,
            ]),
        ]);
    }
}
'@

Write-ProjectFile 'app/Services/Telegram/TelegramService.php' @'
<?php

namespace App\Services\Telegram;

use App\Enums\ResponseTemplateChannel;
use App\Enums\TelegramEventType;
use App\Enums\TelegramLogStatus;
use App\Jobs\Telegram\SendSystemTelegramAlertJob;
use App\Jobs\Telegram\SendTelegramNotificationJob;
use App\Models\Article;
use App\Models\BuildLog;
use App\Models\ResponseTemplate;
use App\Models\TelegramLog;
use App\Models\User;
use App\Models\WebsiteMessage;
use App\Services\Logs\ActivityLogService;
use App\Services\Templates\PlaceholderRenderService;
use App\Services\Templates\ResponseTemplateService;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;
use Throwable;

class TelegramService
{
    public const INQUIRY_RECEIVED_TEMPLATE_SLUG = 'lead-received-admin-telegram';
    public const ARTICLE_PUBLISHED_TEMPLATE_SLUG = 'article-published-telegram';
    public const BUILD_FAILED_TEMPLATE_SLUG = 'astro-build-failed-telegram';
    public const CRITICAL_ALERT_TEMPLATE_SLUG = 'critical-system-alert-telegram';

    public function __construct(
        private readonly ResponseTemplateService $responseTemplates,
        private readonly PlaceholderRenderService $placeholderRenderer,
        private readonly TelegramNotificationFormatter $formatter,
        private readonly ActivityLogService $activityLogs,
    ) {
    }

    public function queueInquiryReceivedNotification(WebsiteMessage $message): TelegramLog
    {
        return $this->queueTemplatedNotification(
            TelegramEventType::INQUIRY_RECEIVED,
            self::INQUIRY_RECEIVED_TEMPLATE_SLUG,
            $this->buildInquiryVariables($message),
            $message,
            ['flow' => 'website_inquiry'],
        );
    }

    public function queueArticlePublishedNotification(Article $article): TelegramLog
    {
        return $this->queueTemplatedNotification(
            TelegramEventType::ARTICLE_PUBLISHED,
            self::ARTICLE_PUBLISHED_TEMPLATE_SLUG,
            [
                'article_title' => $article->title,
                'article_slug' => $article->slug,
                'published_at' => $article->published_at?->format('Y-m-d H:i:s'),
                'created_at' => $article->created_at?->format('Y-m-d H:i:s'),
                'admin_reference' => 'Article #'.$article->id,
            ],
            null,
            ['article_id' => $article->id],
        );
    }

    public function queueBuildFailedNotification(BuildLog $buildLog): TelegramLog
    {
        return $this->queueTemplatedNotification(
            TelegramEventType::ASTRO_BUILD_FAILED,
            self::BUILD_FAILED_TEMPLATE_SLUG,
            [
                'environment' => $buildLog->environment,
                'status' => $buildLog->status,
                'error_message' => $buildLog->output,
                'started_at' => $buildLog->started_at?->format('Y-m-d H:i:s'),
                'finished_at' => $buildLog->finished_at?->format('Y-m-d H:i:s'),
                'created_at' => $buildLog->created_at?->format('Y-m-d H:i:s'),
                'admin_reference' => 'Build #'.$buildLog->id,
            ],
            null,
            ['build_log_id' => $buildLog->id],
        );
    }

    public function queueSystemAlert(string $title, string $message, array $context = []): TelegramLog
    {
        return $this->queueTemplatedNotification(
            TelegramEventType::CRITICAL_SYSTEM_ERROR,
            self::CRITICAL_ALERT_TEMPLATE_SLUG,
            [
                'alert_title' => $title,
                'alert_message' => $message,
                'occurred_at' => now()->format('Y-m-d H:i:s'),
                'context_json' => $context,
                'created_at' => now()->format('Y-m-d H:i:s'),
                'admin_reference' => 'System Alert',
            ],
            null,
            ['context' => $context],
            true,
        );
    }

    public function queueTestNotification(User $actor, ?string $message = null): TelegramLog
    {
        try {
            if (! $this->isConfigured()) {
                return $this->createFailedLog(
                    TelegramEventType::TEST_NOTIFICATION,
                    config('telegram.chat_id', 'unconfigured'),
                    'Telegram integration is not configured.',
                    null,
                    null,
                    ['triggered_by' => $actor->id],
                );
            }

            $log = TelegramLog::query()->create([
                'chat_id' => (string) config('telegram.chat_id'),
                'event_type' => TelegramEventType::TEST_NOTIFICATION,
                'rendered_message' => $this->formatter->formatTestMessage($actor->name, $message),
                'status' => TelegramLogStatus::PENDING,
                'meta_json' => [
                    'triggered_by' => $actor->id,
                ],
            ]);

            SendTelegramNotificationJob::dispatch($log->id);

            return $log;
        } catch (Throwable $exception) {
            report($exception);

            return $this->createFailedLog(
                TelegramEventType::TEST_NOTIFICATION,
                config('telegram.chat_id', 'unconfigured'),
                $exception->getMessage(),
                null,
                null,
                ['triggered_by' => $actor->id],
            );
        }
    }

    public function sendTelegramLogById(int $logId): void
    {
        $log = TelegramLog::query()->find($logId);

        if (! $log) {
            return;
        }

        $this->send($log);
    }

    public function markFailedById(int $logId, string $errorMessage): void
    {
        $log = TelegramLog::query()->find($logId);

        if (! $log || $log->status === TelegramLogStatus::SENT) {
            return;
        }

        $log->forceFill([
            'status' => TelegramLogStatus::FAILED,
            'error_message' => $errorMessage,
        ])->save();
    }

    public function isConfigured(): bool
    {
        return (bool) config('telegram.enabled')
            && filled(config('telegram.bot_token'))
            && filled(config('telegram.chat_id'));
    }

    private function queueTemplatedNotification(
        TelegramEventType $eventType,
        string $templateSlug,
        array $variables,
        ?WebsiteMessage $websiteMessage,
        array $meta,
        bool $systemAlert = false,
    ): TelegramLog {
        $log = null;

        try {
            if (! $this->isConfigured()) {
                return $this->createFailedLog(
                    $eventType,
                    config('telegram.chat_id', 'unconfigured'),
                    'Telegram integration is disabled or incomplete.',
                    $websiteMessage,
                    null,
                    $meta,
                );
            }

            $template = $this->resolveActiveTemplate($templateSlug);
            $renderedMessage = $this->formatter->finalize(
                $this->placeholderRenderer->render(
                    $template->body,
                    $variables,
                    $template->variables_json ?? [],
                    fn (mixed $value): string => $this->formatter->normalizeValue($value),
                ) ?? '',
            );

            $log = TelegramLog::query()->create([
                'website_message_id' => $websiteMessage?->getKey(),
                'template_id' => $template->getKey(),
                'chat_id' => (string) config('telegram.chat_id'),
                'event_type' => $eventType,
                'rendered_message' => $renderedMessage,
                'status' => TelegramLogStatus::PENDING,
                'meta_json' => array_merge($meta, [
                    'template_slug' => $templateSlug,
                ]),
            ]);

            if ($systemAlert) {
                SendSystemTelegramAlertJob::dispatch($log->id);
            } else {
                SendTelegramNotificationJob::dispatch($log->id);
            }

            return $log;
        } catch (Throwable $exception) {
            report($exception);

            if ($log instanceof TelegramLog) {
                $log->forceFill([
                    'status' => TelegramLogStatus::FAILED,
                    'error_message' => $exception->getMessage(),
                ])->save();

                return $log;
            }

            return $this->createFailedLog(
                $eventType,
                config('telegram.chat_id', 'unconfigured'),
                $exception->getMessage(),
                $websiteMessage,
                null,
                $meta,
            );
        }
    }

    private function send(TelegramLog $log): TelegramLog
    {
        $log->forceFill([
            'status' => TelegramLogStatus::PENDING,
            'error_message' => null,
        ])->save();

        try {
            $response = Http::baseUrl((string) config('telegram.base_url'))
                ->timeout(10)
                ->post('/bot'.config('telegram.bot_token').'/sendMessage', [
                    'chat_id' => $log->chat_id,
                    'text' => $log->rendered_message,
                    'disable_web_page_preview' => true,
                ]);

            if ($response->failed() || ! data_get($response->json(), 'ok')) {
                throw new \RuntimeException(
                    data_get($response->json(), 'description', 'Telegram API request failed.'),
                );
            }

            $log->forceFill([
                'status' => TelegramLogStatus::SENT,
                'telegram_message_id' => (string) data_get($response->json(), 'result.message_id'),
                'sent_at' => now(),
                'error_message' => null,
            ])->save();

            $this->activityLogs->record(
                'telegram.sent',
                'Telegram notification delivered successfully.',
                null,
                request(),
                $log->websiteMessage,
                ['telegram_log_id' => $log->id],
            );

            return $log;
        } catch (Throwable $exception) {
            $log->forceFill([
                'status' => TelegramLogStatus::FAILED,
                'error_message' => $exception->getMessage(),
            ])->save();

            $this->activityLogs->record(
                'telegram.failed',
                'Telegram notification failed to send.',
                null,
                request(),
                $log->websiteMessage,
                ['telegram_log_id' => $log->id],
            );

            throw $exception;
        }
    }

    private function buildInquiryVariables(WebsiteMessage $message): array
    {
        return [
            'name' => $message->name,
            'email' => $message->email,
            'company' => $message->company,
            'phone' => $message->phone,
            'subject' => $message->subject,
            'message' => $message->message,
            'message_preview' => Str::limit(trim(preg_replace('/\s+/', ' ', strip_tags($message->message))), 180),
            'source_page' => $message->source_page ?: ($message->metadata['referrer'] ?? ''),
            'created_at' => $message->created_at?->format('Y-m-d H:i:s'),
            'admin_reference' => 'Message #'.$message->id,
        ];
    }

    private function resolveActiveTemplate(string $slug): ResponseTemplate
    {
        $template = $this->responseTemplates->findActiveBySlugAndChannel($slug, ResponseTemplateChannel::TELEGRAM);

        if (! $template) {
            throw new \RuntimeException('Active telegram template not found for slug ['.$slug.'].');
        }

        return $template;
    }

    private function createFailedLog(
        TelegramEventType $eventType,
        mixed $chatId,
        string $errorMessage,
        ?WebsiteMessage $websiteMessage,
        ?ResponseTemplate $template,
        array $meta,
    ): TelegramLog {
        return TelegramLog::query()->create([
            'website_message_id' => $websiteMessage?->getKey(),
            'template_id' => $template?->getKey(),
            'chat_id' => (string) $chatId,
            'event_type' => $eventType,
            'rendered_message' => 'Telegram notification could not be prepared.',
            'status' => TelegramLogStatus::FAILED,
            'error_message' => $errorMessage,
            'meta_json' => $meta,
        ]);
    }
}
'@

Write-ProjectFile 'app/Http/Controllers/Admin/IntegrationController.php' @'
<?php

namespace App\Http\Controllers\Admin;

use App\Enums\TelegramLogStatus;
use App\Http\Controllers\Api\ApiController;
use App\Http\Requests\Integrations\TestTelegramNotificationRequest;
use App\Http\Resources\IntegrationStatusResource;
use App\Http\Resources\TelegramLogResource;
use App\Services\Integrations\IntegrationStatusService;
use App\Services\Telegram\TelegramService;
use Illuminate\Http\JsonResponse;

class IntegrationController extends ApiController
{
    public function status(IntegrationStatusService $integrations): IntegrationStatusResource
    {
        return IntegrationStatusResource::make($integrations->status());
    }

    public function testTelegram(
        TestTelegramNotificationRequest $request,
        TelegramService $telegram,
    ): JsonResponse {
        $log = $telegram->queueTestNotification(
            $request->user(),
            $request->validated('message'),
        );

        $queued = $log->status === TelegramLogStatus::PENDING;

        return $this->message(
            $queued ? 'Telegram test notification queued.' : 'Telegram test notification could not be queued.',
            $queued ? 202 : 200,
            [
                'telegram_log' => TelegramLogResource::make($log),
            ],
        );
    }
}
'@
