<?php

namespace App\Components\Claim;

use App\Models\Claim\Claim;
use App\Models\Claim\Status;
use App\Services\ClaimService;
use App\Services\HistoryService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;

class EditStatus extends Component {
    use AuthorizesRequests;

    public Claim $claim;

    public bool $showHistory = false;

    public ?int $status_id = null;
    private Status $status;

    public function mount(Claim $claim) {
        $this->claim = $claim;
        $this->status_id = $claim->status_id;
        $this->status = $claim->status;
    }

    public function updateStatus(ClaimService $claimService, HistoryService $service) {
        $this->authorize('claims.status.edit');

        if (!$claimService->updateStatus($this->claim, $this->status_id, $service)) {
            $this->dispatch(
                'toast',
                type: 'error',
                message: 'Can\'t edit the status - it is the same status.'
            );

            return;
        }

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

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

    public function render() {
        return view('components.claim.edit-status', [
            'statuses' => Status::all()
        ]);
    }
}
