<?php

namespace App\Livewire\Documents;

use App\Domain\Document\Enums\DocumentType;
use App\Domain\Document\Models\Document;
use App\Domain\Document\Services\DocumentService;
use App\Domain\Participant\Models\Participant;
use Livewire\Attributes\Locked;
use Livewire\Component;

class ParticipantDocuments extends Component
{
    /**
     * The player whose file this is. Locked because every query below is
     * anchored to it — an unlocked public property is settable from the page
     * in Livewire v4, which would turn that anchor into a suggestion. The
     * branch itself is enforced by Participant's strict BranchScope, so
     * binding a player from another branch already 404s.
     */
    #[Locked]
    public Participant $participant;

    public function mount(Participant $participant): void
    {
        $this->participant = $participant;
    }

    public function delete(string $uuid, DocumentService $service): void
    {
        $this->authorize('documents.delete');

        // Anchored to the bound participant, not just the uuid. $uuid arrives
        // straight off a wire:click, so a lookup by uuid alone deletes any
        // document whose uuid the caller has seen — another player's, and
        // (before `documents` grew a branch of its own) another branch's.
        // Document's BranchScope now covers the branch half; this covers the
        // rest, which the scope cannot: one player's file is not another's.
        $document = Document::where('documentable_type', Participant::class)
            ->where('documentable_id', $this->participant->id)
            ->where('uuid', $uuid)
            ->firstOrFail();

        $document->delete();

        session()->flash('success', __('تم حذف المستند'));
    }

    public function render()
    {
        $documents = Document::where('documentable_type', Participant::class)
            ->where('documentable_id', $this->participant->id)
            ->with('uploader')
            ->latest()
            ->get();

        return view('livewire.documents.participant-documents', [
            'documents' => $documents,
            'documentTypes' => DocumentType::cases(),
            'hasValidMedical' => app(DocumentService::class)->participantHasValidMedical($this->participant),
        ]);
    }
}
