<?php

namespace App\Livewire\Participants;

use App\Domain\Participant\Models\Participant;
use App\Domain\Portal\Services\PortalRegistrationService;
use App\Domain\Shared\Exceptions\DomainException;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Title;
use Livewire\Component;
use Livewire\WithPagination;

/**
 * Self-registered members waiting for a human to look at them.
 *
 * The duplicate candidates found at signup are shown beside each row, which is
 * the entire point: DuplicateDetectionService has existed for a long time and
 * nothing surfaced its findings, so a second Person for an existing member
 * would appear silently and the two would drift apart forever.
 *
 * Approving is deliberately not automatic and deliberately not something the
 * member can trigger. A stranger's typing is a request, not a membership.
 */
#[Layout('layouts.app')]
#[Title('تسجيلات في انتظار المراجعة')]
class PendingRegistrations extends Component
{
    use WithPagination;

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

    public function approve(int $participantId, PortalRegistrationService $registrations): void
    {
        $this->authorize('participants.update');

        $participant = Participant::whereNull('approved_at')->findOrFail($participantId);

        try {
            $registrations->approve($participant, auth()->user());
            session()->flash('success', __('تم اعتماد التسجيل'));
        } catch (DomainException $e) {
            session()->flash('error', $e->getMessage());
        }
    }

    public function reject(int $participantId): void
    {
        $this->authorize('participants.update');

        // Rejected, not deleted: the person may reapply, staff may want to see
        // that they tried, and deleting a row a guardian account points at
        // orphans the account.
        Participant::whereNull('approved_at')
            ->where('id', $participantId)
            ->update(['status' => 'inactive', 'updated_at' => now()]);

        session()->flash('success', __('تم رفض التسجيل'));
    }

    public function render()
    {
        return view('livewire.participants.pending-registrations', [
            'pending' => Participant::whereNull('approved_at')
                ->where('registration_source', 'online')
                ->with(['person', 'branch', 'guardians.person'])
                ->orderBy('created_at')
                ->paginate(20),
        ]);
    }
}
