<?php

namespace App\Livewire\Admin;

use App\Actions\StartHostOnboarding;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Validate;
use Livewire\Component;

#[Layout('layouts.admin')]
class HostCreate extends Component
{
    #[Validate('required|string|max:255')]
    public string $name = '';

    #[Validate('required|string|exists:datacenters,code,active,1')]
    public string $datacenter = '';

    public function mount(): void
    {
        $this->datacenter = (string) \App\Models\Datacenter::query()->active()->orderBy('name')->value('code');
    }

    #[Validate('required|ip|unique:hosts,public_ip')]
    public string $public_ip = '';

    #[Validate('required|string|min:8')]
    public string $root_password = '';

    public function save(StartHostOnboarding $action)
    {
        $this->authorize('hosts.manage');
        $data = $this->validate();

        $host = $action->run($data);

        return $this->redirectRoute('admin.hosts.show', ['host' => $host->uuid], navigate: true);
    }

    public function render()
    {
        return view('livewire.admin.host-create', [
            'datacenters' => \App\Models\Datacenter::query()->active()->orderBy('name')->get(),
        ]);
    }
}
