<?php

namespace App\Components\Institution;

use App\Models\Institution\Institution;
use App\Services\HistoryService;
use Livewire\Component;

class View extends Component {
    public Institution $institution;

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

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

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

        $context = [
            'institution_id' => $this->institution->id,
            'display_name'   => $this->institution->display_name,
        ];

        $this->institution->delete();

        // The institution's own history cascades away with it, so record the
        // deletion against the acting user only.
        $this->history->addForActor("Deleted institution \"{$context['display_name']}\"", $context);
    }

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