<?php

namespace App\Livewire;

use App\Livewire\Concerns\BuildsRunSteps;
use App\Models\Customer;
use App\Models\Order;
use App\Models\ProvisioningRun;
use Livewire\Component;

/**
 * Embedded live provisioning progress for the logged-in customer's order.
 * Polls only itself so the dashboard's charts don't churn. Renders nothing once
 * provisioning has completed.
 */
class CustomerProvisioning extends Component
{
    use BuildsRunSteps;

    private function currentRun(): ?ProvisioningRun
    {
        $user = auth()->user();
        if ($user === null) {
            return null;
        }

        $customer = Customer::query()->where('email', $user->email)->first();
        if ($customer === null) {
            return null;
        }

        return ProvisioningRun::query()
            ->where('subject_type', Order::class)
            ->whereIn('subject_id', $customer->orders()->select('id'))
            ->latest('id')
            ->first();
    }

    public function render()
    {
        $run = $this->currentRun();

        // Show the card while provisioning is in flight OR terminally failed; but
        // only POLL while it can still change (terminal failed must not poll forever).
        $show = $run !== null && $run->status !== ProvisioningRun::STATUS_COMPLETED;
        $polling = $run !== null && in_array($run->status, [
            ProvisioningRun::STATUS_PENDING,
            ProvisioningRun::STATUS_RUNNING,
            ProvisioningRun::STATUS_WAITING,
        ], true);

        return view('livewire.customer-provisioning', [
            'active' => $show,
            'polling' => $polling,
            'failed' => $run?->status === ProvisioningRun::STATUS_FAILED,
            'steps' => $show ? $this->buildRunSteps($run) : [],
        ]);
    }
}
