<?php

namespace App\Components\Dsar;

use App\Jobs\Synapse\ExtractEvidenceFromAttachmentJob;
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 string $activeTab = 'details';

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

    public function setTab(string $tab): void {
        $this->activeTab = $tab;
    }

    public function runEvidenceExtraction(): void {
        $this->authorize('synapse.use');

        foreach ($this->dsar->evidenceAttachments() as $attachment) {
            ExtractEvidenceFromAttachmentJob::dispatch($attachment->id, $this->dsar->id);
        }

        session()->flash('success', 'Evidence extraction queued for all DSAR response attachments.');
    }
    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,
        ]);
    }
}
