<?php

namespace App\Provisioning\Events;

use App\Models\Order;
use App\Models\ProvisioningRun;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

/**
 * Broadcast on every recorded run event so admin/customer views update live.
 */
class StepAdvanced implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public function __construct(
        public string $runUuid,
        public string $step,
        public string $outcome,
        public int $currentStep,
        public string $status,
    ) {}

    /** @return array<int, PrivateChannel> */
    public function broadcastOn(): array
    {
        $channels = [new PrivateChannel('admin.runs')];

        // Scope customer runs to their own private channel for the dashboard.
        $run = ProvisioningRun::query()->where('uuid', $this->runUuid)->first();
        if ($run !== null && $run->subject_type === Order::class) {
            $customerId = $run->subject?->customer_id;
            if ($customerId !== null) {
                $channels[] = new PrivateChannel('customer.'.$customerId.'.run');
            }
        }

        return $channels;
    }

    public function broadcastAs(): string
    {
        return 'StepAdvanced';
    }
}
