<?php

namespace App\Notifications;

use App\Models\Post;
use App\Models\User;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
use Illuminate\Support\Str;

class NewPostNotification extends Notification
{
    public function __construct(public Post $post, public User $author) {}

    public function via(object $notifiable): array
    {
        $ch = [];
        if ($notifiable->notificationPref('notif_new_post_from_sub'))   $ch[] = 'database';
        if ($notifiable->notificationPref('email_new_post_from_sub'))   $ch[] = 'mail';
        return $ch;
    }

    public function toArray(object $notifiable): array
    {
        return [
            'type'            => 'new_post',
            'post_id'         => $this->post->id,
            'author_id'       => $this->author->id,
            'author_name'     => $this->author->name,
            'author_avatar'   => $this->author->avatar_url,
            'author_channel'  => $this->author->channel,
            'post_preview'    => Str::limit(strip_tags($this->post->body ?? ''), 100),
        ];
    }

    public function toMail(object $notifiable): MailMessage
    {
        return (new MailMessage)
            ->subject($this->author->name . ' posted something new')
            ->view('emails.new-post-from-sub', [
                'post'      => $this->post,
                'author'    => $this->author,
                'recipient' => $notifiable,
            ]);
    }
}
