<?php

namespace App\Components\PensionCase;

use App\Models\Claim\Status;
use App\Models\PensionCase\PensionCase;
use App\Services\PensionCaseService;
use Livewire\Component;

class EditStatus extends Component {
    public PensionCase $pensionCase;

    public bool $showHistory = false;

    public ?int $status_id = null;

    public function mount(PensionCase $pensionCase): void {
        $this->pensionCase = $pensionCase;
        $this->status_id = $pensionCase->status_id;
    }

    public function updateStatus(PensionCaseService $service): void {
        if (!$this->status_id) {
            return;
        }

        if (!$service->updateStatus($this->pensionCase, $this->status_id)) {
            $this->dispatch('toast', type: 'error', message: 'Status is already set to that value.');
            return;
        }

        $this->pensionCase = $this->pensionCase->fresh(['status', 'statusHistory.status']);

        $this->dispatch('status-updated', pensionCaseId: $this->pensionCase->id);

        $this->dispatch('toast', type: 'success', message: 'Status updated.');
    }

    public function render(): \Illuminate\View\View {
        $type = 'pension-' . $this->pensionCase->claim_type;

        return view('components.pension-case.edit-status', [
            'statuses' => Status::forType($type)->get(),
        ]);
    }
}
