<?php

namespace App\Livewire\Admin;

use App\Models\Instance;
use Illuminate\Support\Facades\Lang;
use Livewire\Attributes\Layout;
use Livewire\Component;
use Livewire\WithPagination;

/**
 * Every instance on the estate, from the instances table.
 *
 * This page used to list seven invented instances on four invented hosts,
 * complete with a Nextcloud version column. The version is not recorded
 * anywhere, so the column is gone rather than filled in with something
 * plausible — and the storage column now shows the quota that was actually
 * sold, not a made-up "used of total", because used disk is not collected.
 */
#[Layout('layouts.admin')]
class Instances extends Component
{
    use WithPagination;

    public function render()
    {
        $instances = Instance::query()
            ->with(['customer', 'host'])
            ->orderByDesc('id')
            ->paginate(25);

        return view('livewire.admin.instances', [
            'instances' => $instances,
            'rows' => $instances->getCollection()->map(fn (Instance $i) => [
                // The operator list shows what is actually served — an unverified
                // custom domain is a plan, not an address.
                'address' => $i->domainIsVerified() ? $i->custom_domain : $i->subdomain,
                'customer' => $i->customer?->name ?? '—',
                'host' => $i->host?->name ?? '—',
                'vmid' => $i->vmid ?? '—',
                'plan' => $i->plan !== null ? __('billing.plan.'.$i->plan) : '—',
                'quota' => $i->quota_gb !== null ? $i->quota_gb.' GB' : '—',
                'status' => $status = $i->status ?? 'provisioning',
                // A status the lifecycle adds later must show as itself, never
                // as "admin.status.whatever" in front of the owner.
                'status_label' => Lang::has('admin.status.'.$status)
                    ? __('admin.status.'.$status)
                    : $status,
            ])->all(),
        ]);
    }
}
