<?php

namespace App\Components\Dsar;

use App\Enum\Dsar\DsarStatus;
use App\Models\Dsar\Dsar;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;

class View extends Component {
    use AuthorizesRequests;
    public Dsar $dsar;

    public function mount(): void {
        $this->authorize('dsars.view');
    }

    public function updateStatus(string $status): void {
        $this->authorize('dsars.batch.send');
        if (!in_array($status, DsarStatus::manuallySelectable(), true)) {
            return;
        }
        $this->dsar->update(['status' => $status]);
        $this->dispatch('toast', message: 'Status updated.', type: 'success');
    }

    public function deleteDsar(): mixed {
        $this->authorize('delete', $this->dsar);
        $client = $this->dsar->claim->client;
        $this->dsar->delete();
        return redirect()->route('clients.show', $client);
    }

    public function updateDueDate(?string $date): void {
        $this->authorize('dsars.batch.send');
        $this->dsar->update(['expected_at' => $date ?: null]);
        $this->dispatch('toast', message: 'Due date updated.', type: 'success');
    }

    public function render() {
        $this->dsar->loadMissing(['institution', 'outboundMessage', 'latestResponse', 'claim.client']);

        $emailSend = $this->dsar->outboundMessage;

        return view('components.dsar.view', [
            'institution' => $this->dsar->institution,
            'emailSend'   => $emailSend,
        ]);
    }
}
