<?php

namespace App\Notifications;

use App\Models\Comment;
use App\Models\Task;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Notifications\Notification;

class TaskCommentNotification extends Notification implements ShouldBroadcast
{
    use Queueable;

    public function __construct(public Task $task, public Comment $comment) {}

    public function via($notifiable): array
    {
        return ['database', 'broadcast'];
    }

    public function toArray($notifiable): array
    {
        return [
            'type' => 'task_comment',
            'task_id' => $this->task->id,
            'project_id' => $this->task->project_id,
            'comment_id' => $this->comment->id,
            'message' => "Nuevo comentario en '{$this->task->title}' por {$this->comment->user->name}: ".substr($this->comment->body, 0, 100),
        ];
    }

    public function broadcastOn(): array
    {
        $userIds = [];
        if ($this->task->assigned_to) $userIds[] = $this->task->assigned_to;
        if ($this->task->created_by) $userIds[] = $this->task->created_by;
        return array_map(fn ($id) => new \Illuminate\Broadcasting\PrivateChannel("user.{$id}"), array_unique($userIds));
    }
}