<?php

namespace App\Components\Claim;

use App\Models\Claim\Claim;
use App\Models\Dsar\DsarEvidenceItem;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Component;

class EvidenceOverview extends Component
{
    use AuthorizesRequests;

    public Claim $claim;

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

    public function render()
    {
        $dsars = $this->claim->dsars()->with(['institution'])->get();

        $dsarData = $dsars->map(function ($dsar) {
            $attachments = $dsar->evidenceAttachments();

            $items = $attachments->flatMap(fn ($a) => $a->evidenceItems);

            $byCategory = $items->groupBy('category')
                ->map(fn ($group) => $group->count())
                ->sortDesc();

            return [
                'dsar'        => $dsar,
                'attachments' => $attachments,
                'totalItems'  => $items->count(),
                'confirmed'   => $items->filter->isConfirmed()->count(),
                'dismissed'   => $items->filter->isDismissed()->count(),
                'unreviewed'  => $items->filter->isUnreviewed()->count(),
                'byCategory'  => $byCategory,
                'highCount'   => $items->where('severity', 'high')->count(),
            ];
        })->filter(fn ($d) => $d['attachments']->isNotEmpty() || $d['totalItems'] > 0);

        return view('components.claim.evidence-overview', [
            'dsarData' => $dsarData,
        ]);
    }
}
