<?php

namespace App\Listeners;

use App\Enums\RegistrationStatus;
use App\Events\RegistrationStatusChanged;
use App\Notifications\EventRegistrationConfirmedNotification;
use App\Notifications\EventRegistrationReceivedNotification;
use App\Notifications\EventRegistrationRejectedNotification;
use App\Notifications\EventRegistrationWaitlistedNotification;
use App\Notifications\ManualPaymentRequiredNotification;
use App\Notifications\WaitlistPromotedNotification;

class SendRegistrationStatusNotification
{
    public bool $afterCommit = true;

    public function handle(RegistrationStatusChanged $event): void
    {
        $registration = $event->registration->loadMissing(['event', 'user']);
        $user = $registration->user;

        if ($event->wasPromotedFromWaitlist) {
            $user->notify(new WaitlistPromotedNotification($registration));

            return;
        }

        if ($event->isNewRegistration) {
            $user->notify(new EventRegistrationReceivedNotification($registration));

            if ($registration->status === RegistrationStatus::PendingPayment) {
                $user->notify(new ManualPaymentRequiredNotification($registration));
            }

            if ($registration->status === RegistrationStatus::Waitlisted) {
                $user->notify(new EventRegistrationWaitlistedNotification($registration));
            }

            return;
        }

        match ($registration->status) {
            RegistrationStatus::Confirmed => $user->notify(new EventRegistrationConfirmedNotification($registration)),
            RegistrationStatus::Rejected => $user->notify(new EventRegistrationRejectedNotification($registration, $event->reason)),
            RegistrationStatus::Waitlisted => $user->notify(new EventRegistrationWaitlistedNotification($registration)),
            RegistrationStatus::PendingPayment => $user->notify(new ManualPaymentRequiredNotification($registration)),
            default => null,
        };
    }
}
