<?php

namespace App\Components\Institution;

use App\Models\Institution\Institution;
use App\Services\HistoryService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;

class View extends Component {
    use AuthorizesRequests;
    public Institution $institution;

    public function mount() {
        $this->authorize('view', $this->institution);
    }

    public function boot(HistoryService $history): void {
        $this->history = $history;
    }

    public function deleteInstitution() {
        $this->authorize('delete', $this->institution);

        if ($this->institution->hasAttachedClients()) {
            $this->dispatch('toast', message: 'Cannot delete: this institution is attached to one or more clients.', type: 'danger');
            return;
        }

        $this->institution->delete();

        $this->history->add($this->institution, "Institution deleted.");

        $this->history->add(auth()->user(), "Deleted institution {$this->institution->display_name}.");
    }

    public function render() {
        return view('components.institution.view', [
            'hasClients' => $this->institution->hasAttachedClients(),
        ]);
    }
}
