<?php

namespace App\Notifications;

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

class InspectionUpdatedNotification extends Notification implements ShouldBroadcast
{
    use Queueable;

    public function __construct(public Inspection $inspection, public array $changes = []) {}

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

    public function toArray($notifiable): array
    {
        return [
            'type' => 'inspection_updated',
            'inspection_id' => $this->inspection->id,
            'project_id' => $this->inspection->project_id,
            'feature_name' => $this->inspection->feature?->name ?? '—',
            'template_name' => $this->inspection->template?->name ?? '—',
            'result' => $this->inspection->result,
            'changes' => $this->changes,
            'message' => "Inspección actualizada en '{$this->inspection->feature?->name}'",
        ];
    }

    public function broadcastOn(): array
    {
        $userIds = $this->inspection->project->users->pluck('id')->toArray();
        return array_map(fn ($id) => new \Illuminate\Broadcasting\PrivateChannel("user.{$id}"), $userIds);
    }
}