<?php

namespace App\Components\WillsCase;

use App\Models\Claim\Status;
use App\Models\WillsCase\WillsCase;
use App\Services\WillsCaseService;
use Livewire\Component;

class EditStatus extends Component {
    public WillsCase $willsCase;

    public bool $showHistory = false;

    public ?int $status_id = null;

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

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

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

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

        $this->dispatch('status-updated', willsCaseId: $this->willsCase->id);

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

    public function render(): \Illuminate\View\View {
        return view('components.wills-case.edit-status', [
            'statuses' => Status::forType('wills')->get(),
        ]);
    }
}
