<?php

namespace App\Events;

use App\Models\Task;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class ProjectTaskStageChanged implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    /**
     * Create a new event instance.
     */
    public function __construct(public Task $task)
    {
        $this->task->loadMissing(['projectStage', 'assignee', 'creator']);
    }

    public function broadcastOn(): PrivateChannel
    {
        return new PrivateChannel('projects.'.$this->task->project_id);
    }

    public function broadcastAs(): string
    {
        return 'project.task-stage-changed';
    }

    /**
     * @return array<string, mixed>
     */
    public function broadcastWith(): array
    {
        return [
            'id' => $this->task->id,
            'title' => $this->task->title,
            'project_id' => $this->task->project_id,
            'project_stage_id' => $this->task->project_stage_id,
            'project_stage_name' => $this->task->projectStage?->name,
            'status' => $this->task->status,
            'priority' => $this->task->priority,
            'assignee_name' => $this->task->assignee?->name,
            'creator_name' => $this->task->creator?->name,
            'due_at' => $this->task->due_at?->toIso8601String(),
            'tracked_hours' => (float) $this->task->tracked_hours,
            'estimated_hours' => (float) $this->task->estimated_hours,
            'url' => route('tasks.show', $this->task),
            'edit_url' => route('tasks.edit', $this->task),
        ];
    }
}
