<?php

namespace App\Actions\Payments;

use App\Enums\PaymentProofReviewStatus;
use App\Enums\PaymentStatus;
use App\Enums\RegistrationStatus;
use App\Events\PaymentProofReviewed;
use App\Models\EventPaymentProof;
use App\Models\User;
use App\Services\AuditLogger;
use App\Services\RegistrationStatusService;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;

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

    public function execute(EventPaymentProof $proof, User $admin, string $reason): EventPaymentProof
    {
        return DB::transaction(function () use ($proof, $admin, $reason) {
            if ($proof->review_status !== PaymentProofReviewStatus::Pending) {
                throw new InvalidArgumentException(__('events.errors.invalid_status'));
            }

            $registration = $proof->eventRegistration;

            $proof->update([
                'review_status' => PaymentProofReviewStatus::Rejected,
                'reviewed_by' => $admin->id,
                'reviewed_at' => now(),
                'rejection_reason' => $reason,
            ]);

            $oldStatus = $registration->status;

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

            $registration->update([
                'payment_status' => PaymentStatus::Rejected,
            ]);

            $this->auditLogger->log('payment.rejected', $proof, null, ['review_status' => PaymentProofReviewStatus::Rejected->value, 'reason' => $reason]);

            event(new PaymentProofReviewed(
                proof: $proof->fresh(['eventRegistration.event', 'eventRegistration.user']),
                action: PaymentProofReviewed::ACTION_REJECTED,
                reason: $reason,
            ));

            return $proof->fresh(['eventRegistration.event', 'manualPaymentMethod']);
        });
    }
}
