<?php

namespace App\Notifications;

use App\Models\Message;
use App\Services\Auth\PortalRedirectService;
use Illuminate\Notifications\Messages\MailMessage;

class NewMessageNotification extends BaseSchoolNotification
{
    public function __construct(public Message $message) {}

    public function toMail(object $notifiable): MailMessage
    {
        $sender = $this->message->sender?->name ?? 'School staff';

        return $this->mailMessage(
            subject: 'New message: '.($this->message->subject ?? 'No subject'),
            greeting: 'Hello '.$notifiable->name.',',
            line: "{$sender} sent you a message: ".str($this->message->body)->limit(120),
            actionUrl: url($this->inboxUrl($notifiable)),
            actionText: 'Read Message',
        );
    }

    /**
     * @return array<string, mixed>
     */
    public function toArray(object $notifiable): array
    {
        return $this->databasePayload(
            title: 'New message',
            body: ($this->message->subject ?? 'Message').' from '.($this->message->sender?->name ?? 'Staff'),
            type: 'message',
            url: $this->inboxUrl($notifiable),
        );
    }

    private function inboxUrl(object $notifiable): string
    {
        $route = app(PortalRedirectService::class)->homeRouteName($notifiable);

        return match (true) {
            str_starts_with($route, 'parent.') => '/parent/messages',
            str_starts_with($route, 'student.') => '/student/messages',
            str_starts_with($route, 'teacher.') => '/teacher/messages',
            str_starts_with($route, 'staff.') => '/staff/messages',
            default => '/dashboard',
        };
    }
}
