<?php

namespace App\Components\Institution;

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

class Merge extends Component {
    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);

        $careSettingsMoved = $this->institution->careSettings()->count();
        $claimsMoved = $this->institution->claims()->count();

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

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

        $context = [
            'source_institution_id' => $this->institution->id,
            'source_name'           => $this->institution->display_name,
            'target_institution_id' => $target->id,
            'target_name'           => $target->display_name,
            'care_settings_moved'   => $careSettingsMoved,
            'claims_moved'          => $claimsMoved,
        ];

        $history->add($this->institution, "This institution's records merged into \"{$target->display_name}\"", $context);
        $history->add($target, "Records from \"{$this->institution->display_name}\" merged into this institution", $context);

        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()
        ]);
    }
}
