<?php

namespace App\Components\Dsar;

use App\Jobs\Synapse\ExtractEvidenceFromAttachmentJob;
use App\Models\Dsar\Dsar;
use App\Models\Dsar\DsarEvidenceItem;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Attributes\On;
use Livewire\Component;

class EvidenceManager extends Component
{
    use AuthorizesRequests;

    public Dsar $dsar;

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

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

        ExtractEvidenceFromAttachmentJob::dispatch($attachmentId, $this->dsar->id);
    }

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

        foreach ($this->dsar->evidenceAttachments() as $attachment) {
            if (!in_array($attachment->evidence_status, ['processing', 'completed'], true)) {
                ExtractEvidenceFromAttachmentJob::dispatch($attachment->id, $this->dsar->id);
            }
        }
    }

    #[On('evidenceItemUpdated')]
    public function refreshItems(): void {}

    public function render()
    {
        $attachments = $this->dsar->evidenceAttachments();

        $totalItems     = 0;
        $confirmedCount = 0;
        $dismissedCount = 0;
        $unreviewedCount = 0;

        foreach ($attachments as $a) {
            foreach ($a->evidenceItems as $item) {
                $totalItems++;
                if ($item->isConfirmed()) $confirmedCount++;
                elseif ($item->isDismissed()) $dismissedCount++;
                else $unreviewedCount++;
            }
        }

        return view('components.dsar.evidence-manager', [
            'attachments'     => $attachments,
            'totalItems'      => $totalItems,
            'confirmedCount'  => $confirmedCount,
            'dismissedCount'  => $dismissedCount,
            'unreviewedCount' => $unreviewedCount,
        ]);
    }
}
