<?php

namespace App\Notifications;

use App\Models\Tenant;
use App\Models\TenantAnnouncement;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

class TenantAnnouncementNotification extends Notification implements ShouldQueue
{
    use Queueable;

    /**
     * Create a new notification instance.
     */
    public function __construct(
        private readonly TenantAnnouncement $announcement,
        private readonly Tenant $tenant,
    ) {
        $this->afterCommit();
    }

    /**
     * Get the notification's delivery channels.
     *
     * @return array<int, string>
     */
    public function via(object $notifiable): array
    {
        return ['mail'];
    }

    /**
     * Get the mail representation of the notification.
     */
    public function toMail(object $notifiable): MailMessage
    {
        $lines = collect(preg_split('/\r\n|\r|\n/', $this->announcement->body ?? ''))
            ->map(fn ($line) => trim($line ?? ''))
            ->filter()
            ->values()
            ->all();

        $ctaLabel = $this->announcement->cta_label ?: 'Event-Admin öffnen';
        $ctaUrl = $this->announcement->cta_url ?: url('/event-admin');

        return (new MailMessage)
            ->subject($this->announcement->title)
            ->view('emails.notifications.basic', [
                'title' => $this->announcement->title,
                'preheader' => $this->announcement->title,
                'heroTitle' => $this->announcement->title,
                'lines' => $lines,
                'cta' => [
                    [
                        'label' => $ctaLabel,
                        'url' => $ctaUrl,
                    ],
                ],
            ]);
    }

    /**
     * Get the array representation of the notification.
     *
     * @return array<string, mixed>
     */
    public function toArray(object $notifiable): array
    {
        return [
            'announcement_id' => $this->announcement->getKey(),
            'tenant_id' => $this->tenant->getKey(),
        ];
    }
}
