<?php

namespace App\Livewire\Admin;

use App\Models\Datacenter;
use App\Models\Host;
use Illuminate\Database\QueryException;
use LivewireUI\Modal\ModalComponent;

/**
 * Confirmation for deleting a datacenter (R5). Guarded: a datacenter that still
 * has hosts cannot be deleted — it would orphan host placement — so the modal
 * blocks and explains instead. Otherwise it is safe to hard-delete an unused code.
 */
class ConfirmDeleteDatacenter extends ModalComponent
{
    public string $uuid;

    public string $name = '';

    public int $hostCount = 0;

    public function mount(string $uuid): void
    {
        $this->authorize('datacenters.manage'); // modals are reachable without the route middleware
        $dc = Datacenter::query()->where('uuid', $uuid)->withCount('hosts')->firstOrFail();
        $this->uuid = $uuid;
        $this->name = $dc->name;
        $this->hostCount = $dc->hosts_count;
    }

    public function delete()
    {
        $this->authorize('datacenters.manage');
        $dc = Datacenter::query()->where('uuid', $this->uuid)->first();
        if ($dc === null) {
            return $this->redirectRoute('admin.datacenters', navigate: true);
        }

        // The hosts.datacenter → datacenters.code foreign key (restrictOnDelete)
        // is the source of truth: the DB refuses to orphan a host. We pre-check
        // for a friendly message and catch the constraint as the race backstop.
        if (Host::query()->where('datacenter', $dc->code)->exists()) {
            return $this->redirectRoute('admin.datacenters', navigate: true);
        }

        try {
            $dc->delete();
        } catch (QueryException) {
            // A host was created for this code concurrently — leave it intact.
        }

        return $this->redirectRoute('admin.datacenters', navigate: true);
    }

    public function render()
    {
        return view('livewire.admin.confirm-delete-datacenter');
    }
}
