<?php

namespace App\Services;

use App\Enums\UserRole;
use App\Models\User;
use Exception;
use Illuminate\Contracts\Encryption\DecryptException;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;

class SubscriptionService
{
    private function generateEncryptedPayload(string $subscriptionKey): string
    {
        return base64_encode(Crypt::encryptString(json_encode([
            'subscription_access_key' => $subscriptionKey,
            'timestamp' => now()->timestamp,
            'nonce' => Str::uuid()->toString(),
        ], JSON_THROW_ON_ERROR)));
    }

    /**
     * Gets the subscription status from the subscription service.
     */
    private function getSubscriptionStatus(string $subscriptionKey): array | null
    {
        try {
            $payload = $this->generateEncryptedPayload($subscriptionKey);

            $response = Http::post(config('services.subscription_service_host').'/api/membership/verify', [
                'payload' => $payload,
            ]);

            if (! $response->successful()) {
                logger()->error('Subscription Service API error', [
                    'status' => $response->status(),
                    'body' => $response->body(),
                ]);

                return null;
            }

            $encryptedResponse = $response->json('payload');

            $json = json_decode(
                Crypt::decryptString($encryptedResponse),
                true,
                flags: JSON_THROW_ON_ERROR
            );

            return $json;
        } catch (Exception $e) {
            logger()->error('getSubscriptionStatus Exception', [
                'details' => $e,
            ]);
        }

        return null;
    }

    public function checkSubscriptionStatus(User $user, string $subscriptionKey): bool
    {
        $subscriptionStatus = $this->getSubscriptionStatus($subscriptionKey);
        if (!$subscriptionStatus) {
            return false;
        }

        if ($subscriptionStatus['valid'] === true && 
            $subscriptionStatus['active'] === true) {
            $user->addRole(UserRole::SUPPORTER);
            return true;
        }

        $user->removeRole(UserRole::SUPPORTER);
        return true;
    }
}
