<?php

namespace App\Http\Controllers\Api\V1;

use App\Domain\Document\Models\Document;
use App\Domain\Participant\Models\Participant;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class DocumentController extends Controller
{
    public function index(string $participantUuid, Request $request): JsonResponse
    {
        $participant = $this->findAuthorized($participantUuid, $request->user());

        $documents = Document::where('documentable_type', 'App\\Domain\\Participant\\Models\\Participant')
            ->where('documentable_id', $participant->id)
            ->orderByDesc('created_at')
            ->get();

        return response()->json([
            'data' => $documents->map(fn ($doc) => [
                'id' => $doc->uuid,
                'type' => $doc->document_type->value,
                'type_label' => $doc->document_type->label(),
                'status' => $doc->status->value,
                'original_filename' => $doc->original_filename,
                'file_url' => $doc->file_path ? asset('storage/' . $doc->file_path) : null,
                'expires_at' => $doc->expires_at?->toDateString(),
                'is_expired' => $doc->isExpired(),
                'rejection_reason' => $doc->rejection_reason,
                'notes' => $doc->notes,
                'uploaded_at' => $doc->created_at?->toIso8601String(),
            ]),
            'summary' => [
                'total' => $documents->count(),
                'pending' => $documents->filter(fn ($d) => $d->isPending())->count(),
                'approved' => $documents->filter(fn ($d) => $d->isApproved())->count(),
                'expired' => $documents->filter(fn ($d) => $d->isExpired())->count(),
            ],
        ]);
    }

    private function findAuthorized(string $uuid, $user): Participant
    {
        $participant = Participant::where('uuid', $uuid)->firstOrFail();
        $personId = $user->person_id;

        if (!$personId) {
            abort(403, 'غير مصرح لك بالوصول لهذا المشترك');
        }

        if ($participant->person_id === $personId) {
            return $participant;
        }

        $guardian = \App\Domain\Identity\Models\Guardian::where('person_id', $personId)->first();
        if ($guardian && $guardian->participants()->where('participants.id', $participant->id)->exists()) {
            return $participant;
        }

        abort(403, 'غير مصرح لك بالوصول لهذا المشترك');
    }
}
