<?php

namespace App\Listeners;

use App\Models\User;
use App\Models\UserNotificationPreference;
use Illuminate\Support\Facades\Cache;
use Laravel\Cashier\Events\WebhookReceived;

class DowngradeUserOnSubscriptionDeleted
{
    public function handle(WebhookReceived $event): void
    {
        if (($event->payload['type'] ?? null) !== 'customer.subscription.deleted') {
            return;
        }

        $stripeCustomerId = $event->payload['data']['object']['customer'] ?? null;

        if (! $stripeCustomerId) {
            return;
        }

        $user = User::where('stripe_id', $stripeCustomerId)->first();

        if (! $user) {
            return;
        }

        UserNotificationPreference::query()
            ->where('user_id', $user->id)
            ->whereIn('channel', ['whatsapp', 'sms'])
            ->update(['enabled' => false]);

        Cache::tags(['plans'])->forget("plan_for_user_{$user->id}");
    }
}
