<?php

declare(strict_types=1);

namespace App\Listeners;

use App\Events\PaymentSucceeded;
use App\Notifications\PaymentSucceededNotification;
use App\Services\Billing\DunningService;
use Illuminate\Support\Facades\Log;
use Laravel\Cashier\Subscription;

class HandlePaymentSucceeded
{
    public function __construct(
        private DunningService $dunningService,
    ) {}

    public function handle(PaymentSucceeded $event): void
    {
        Log::info("Payment succeeded for user #{$event->user->id}", [
            'transaction_id' => $event->transaction->id,
            'amount' => $event->transaction->amount,
        ]);

        $event->user->notify(new PaymentSucceededNotification($event->transaction));

        // Reactivate any suspended services if the user pays an overdue subscription
        $subscriptionId = $event->transaction->subscription_id;

        if ($subscriptionId) {
            $subscription = Subscription::find($subscriptionId);

            if ($subscription && $subscription->stripe_status === 'active') {
                $this->dunningService->reactivateServicesForSubscription($subscription);
            }
        }
    }
}
