<?php

namespace App\Livewire;

use App\Enums\UserRole;
use App\Models\User;
use App\Services\SubscriptionService;
use Livewire\Component;
use Livewire\Attributes\Computed;
use Illuminate\Support\Facades\RateLimiter;

class UserSubscription extends Component
{
    public $userId = 0;

    public $subscriptionKey = '';

    public $isActive = false;

    protected $rules = [
        'subscriptionKey' => 'required|string|size:48',
    ];

    public function mount(User $user)
    {
        $this->userId = $user ? $user->id : auth()->user()->id;
        $this->subscriptionKey = $user->subscription_key ?? '';
        $this->isActive = $user->hasRole(UserRole::SUPPORTER) ?? false;
    }

    public function applyKey(SubscriptionService $subscriptionService)
    {
        $this->validate();

        $rateLimitKey = "apply-subscription:{$this->userId}";
        $rateLimitMinutes = 60 * 5; // 5 minutes

        // Rate Limit to prevent users trying random keys
        if (RateLimiter::tooManyAttempts($rateLimitKey, 1)) {
            $seconds = RateLimiter::availableIn($rateLimitKey);
            $this->addError('subscriptionKey', "Too many attempts. Try again in {$seconds} seconds.");
            return;
        }

        RateLimiter::hit($rateLimitKey, $rateLimitMinutes);

        // Check if token is already being used
        $alreadyUsed = User::where('subscription_key', $this->subscriptionKey)
            ->whereNot('id', $this->userId)
            ->exists();

        if ($alreadyUsed) {
            $this->addError('subscriptionKey', 'Key already used!');
            return;
        }

        $user = User::where('id', $this->userId)->firstOrFail();

        // Verify token
        $success = $subscriptionService->checkSubscriptionStatus($user, $this->subscriptionKey);
        if (!$success) {
            $this->addError('subscriptionKey', 'Invalid Key! If you believe this is a bug, please report this to the admin!');
            return;
        }
        
        $user->subscription_key = $this->subscriptionKey;
        $user->save();
        $this->isActive = true;
    }

    public function render()
    {
        return view('livewire.user-subscription');
    }
}
