<?php

namespace App\Http\Controllers\Client;

use App\Http\Controllers\Controller;
use App\Models\Client\Client;
use App\Services\EvidenceCorpus;
use App\Services\PdfService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Spatie\Browsershot\Browsershot;
use Spatie\LaravelPdf\Facades\Pdf;

class EvidenceReviewExportController extends Controller
{
    use AuthorizesRequests;

    public function __construct(
        private EvidenceCorpus $corpus,
        private PdfService $pdfService,
    ) {}

    public function download(Client $client)
    {
        $this->authorize('view', $client);

        $rows = $this->corpus->forClient($client);

        // Confirmed items only, each carrying its source file row for provenance.
        $confirmed = $rows
            ->flatMap(fn ($r) => $r['items']->map(fn ($i) => ['item' => $i, 'row' => $r]))
            ->filter(fn ($e) => $e['item']->isConfirmed());

        // Accepted care-setting labels for grouping.
        $careSettings = collect();
        if ($client->claim) {
            $careSettings = $client->claim->careSettings()
                ->with('institution')
                ->get()
                ->mapWithKeys(fn ($cs) => [
                    $cs->id => trim(($cs->institution?->display_name ?? 'Unknown care setting')
                        . ($cs->dates ? " ({$cs->dates})" : '')),
                ]);
        }

        // Group by ACCEPTED care setting (suggested-but-unconfirmed tags fall into "Other").
        $groups = $confirmed
            ->groupBy(fn ($e) => ($e['item']->care_setting_id && !$e['item']->care_setting_is_suggested)
                ? $e['item']->care_setting_id
                : 0)
            ->map(fn ($entries, $csId) => [
                'label'       => $csId ? ($careSettings[$csId] ?? 'Unknown care setting') : 'Other confirmed evidence (untagged)',
                'is_untagged' => !$csId,
                'entries'     => $entries->values(),
            ])
            ->sortBy(fn ($g) => $g['is_untagged'] ? PHP_INT_MAX : 0)
            ->values();

        $path     = $this->pdfService->temp('evidence-review');
        $filename = 'Evidence-Review-' . Str::slug($client->fullName ?? (string) $client->id) . '.pdf';

        Pdf::view('pdfs.evidence-review', [
            'client'       => $client,
            'groups'       => $groups,
            'totalItems'   => $confirmed->count(),
            'generatedAt'  => now(),
        ])
            ->margins(30, 30, 30, 30)
            ->withBrowsershot(fn (Browsershot $browsershot) => $this->pdfService->configureBrowsershot($browsershot))
            ->save(Storage::path($path));

        return $this->pdfService->download($path, $filename);
    }
}
