<?php

namespace App\Components\Institution;

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

class KeyInfo extends Component {
    use AuthorizesRequests;
    public Institution $institution;
    public string $content = '';
    public ?Note $note = null;

    public function mount(Institution $institution): void {
        $this->institution = $institution;
        $this->note = $institution->keyInfo()->latest('updated_at')->first();
        $this->content = $this->note?->note ?? '';
    }

    public function save(HistoryService $historyService): void {
        $this->authorize('notes.create');

        $trimmed = trim($this->content);

        if ($trimmed === '') {
            if ($this->note) {
                $this->note->delete();
                $historyService->add($this->institution, 'Key info cleared');
                $this->note = null;
            }
        } elseif ($this->note) {
            $previous = $this->note->note;
            $this->note->update([
                'note'    => $trimmed,
                'user_id' => auth()->id(),
            ]);
            if ($previous !== $trimmed) {
                $historyService->add($this->institution, 'Key info updated');
            }
        } else {
            $this->note = $this->institution->notes()->create([
                'user_id'    => auth()->id(),
                'note'       => $trimmed,
                'is_primary' => true,
            ]);
            $historyService->add($this->institution, 'Key info added');
        }

        $this->content = $this->note?->note ?? '';

        $this->dispatch('toast',
            title: 'Saved',
            message: 'Key info saved.',
            type: 'success'
        );
    }

    public function render() {
        return view('components.institution.key-info');
    }
}
