<?php

namespace App\Notifications;

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

class FeatureCompletedNotification extends Notification implements ShouldBroadcast
{
    use Queueable;

    public function __construct(public Feature $feature) {}

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

    public function toArray($notifiable): array
    {
        return [
            'type' => 'feature_completed',
            'feature_id' => $this->feature->id,
            'project_id' => $this->feature->layer?->phase?->project_id,
            'feature_name' => $this->feature->name,
            'progress' => 100,
            'message' => "Elemento '{$this->feature->name}' marcado como completado",
        ];
    }

    public function broadcastOn(): array
    {
        $projectId = $this->feature->layer?->phase?->project_id;
        if (! $projectId) {
            return [];
        }
        $userIds = \App\Models\Project::find($projectId)?->users->pluck('id')->toArray() ?? [];
        return array_map(fn ($id) => new \Illuminate\Broadcasting\PrivateChannel("user.{$id}"), $userIds);
    }
}