<?php

namespace App\Components\Institution;

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

class Merge extends Component {
    use AuthorizesRequests;
    public Institution $institution;
    public $targetInstitutionId;

    public function merge(HistoryService $history) {
        $this->authorize('institutions.merge');
        $this->validate([
            'targetInstitutionId' => 'required|exists:institutions,id|different:institution.id',
        ]);

        $target = Institution::find($this->targetInstitutionId);

        $this->institution->careSettings()->update([
            'institution_id' => $this->targetInstitutionId
        ]);
        
        $this->institution->claims()->update([
            'institution_id' => $this->targetInstitutionId
        ]);

        $history->add($this->institution, "Merged {$target->display_name} into this institution");
        $history->add($target, "Merged this institution into {$this->institution->display_name}");

        $this->institution->delete();

        return redirect()->route('institutions.show', $target);
    }

    public function render() {
        return view('components.institution.merge', [
            'institutions' => Institution::where('id', '!=', $this->institution->id)
                ->get()
                ->mapWithKeys(fn ($i) => [
                    $i->id => "{$i->displayId} - {$i->display_name}"
                ])
                ->toArray()
        ]);
    }
}
