<?php

namespace App\Notifications;

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

class IssueStatusChangedNotification extends Notification implements ShouldBroadcast
{
    use Queueable;

    public function __construct(public Issue $issue, public string $status) {}

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

    public function toArray($notifiable): array
    {
        $label = [
            'open' => 'reabierta',
            'in_review' => 'enviada a revisión',
            'resolved' => 'resuelta',
            'closed' => 'cerrada',
        ][$this->status] ?? $this->status;

        return [
            'type' => 'issue_status_changed',
            'issue_id' => $this->issue->id,
            'project_id' => $this->issue->project_id,
            'status' => $this->status,
            'message' => "La incidencia '{$this->issue->title}' ha sido {$label}",
        ];
    }

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