<?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 TaskStatusChanged implements ShouldBroadcastNow
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

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

    public function broadcastOn(): PrivateChannel
    {
        return new PrivateChannel('tasks.board');
    }

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

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