<?php

namespace App\Actions\Events;

use App\Enums\RegistrationStatus;
use App\Events\RegistrationStatusChanged;
use App\Models\EventRegistration;
use App\Models\User;
use App\Services\AuditLogger;
use App\Services\RegistrationStatusService;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;

class RejectRegistrationAction
{
    public function __construct(
        private RegistrationStatusService $registrationStatus,
        private AuditLogger $auditLogger,
    ) {}

    public function execute(EventRegistration $registration, User $admin, ?string $reason = null): EventRegistration
    {
        return DB::transaction(function () use ($registration, $admin, $reason) {
            if (! in_array($registration->status, [RegistrationStatus::Pending, RegistrationStatus::Waitlisted], true)) {
                throw new InvalidArgumentException(__('events.errors.invalid_status'));
            }

            $oldStatus = $registration->status;

            $this->registrationStatus->record(
                $registration,
                RegistrationStatus::Rejected,
                $oldStatus,
                $admin,
                $reason,
            );

            $registration->update([
                'reviewed_by' => $admin->id,
                'reviewed_at' => now(),
                'admin_notes' => $reason,
            ]);

            $this->auditLogger->log('registration.rejected', $registration, ['status' => $oldStatus->value], ['status' => RegistrationStatus::Rejected->value]);

            event(new RegistrationStatusChanged(
                registration: $registration->fresh(['event', 'user']),
                previousStatus: $oldStatus,
                reason: $reason,
            ));

            return $registration->fresh(['event', 'user']);
        });
    }
}
