<?php

namespace App\Events;

use App\Models\Deal;
use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

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

    /**
     * Create a new event instance.
     */
    public function __construct(public Deal $deal)
    {
        $this->deal->loadMissing(['stage', 'company', 'contact', 'owner']);
    }

    /**
     * Get the channels the event should broadcast on.
     */
    public function broadcastOn(): Channel
    {
        return new Channel('pipelines.'.$this->deal->pipeline_id);
    }

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

    /**
     * @return array<string, mixed>
     */
    public function broadcastWith(): array
    {
        return [
            'id' => $this->deal->id,
            'title' => $this->deal->title,
            'pipeline_id' => $this->deal->pipeline_id,
            'stage_id' => $this->deal->stage_id,
            'stage_name' => $this->deal->stage?->name,
            'status' => $this->deal->status,
            'amount' => (float) $this->deal->amount,
            'company_name' => $this->deal->company?->name,
            'contact_name' => $this->deal->contact?->full_name,
            'owner_name' => $this->deal->owner?->name,
        ];
    }
}
