<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;
use App\Models\Setting;

class EnvatoService
{
    protected $baseUrl = 'https://api.envato.com';

    /**
     * Get Envato settings from database with fallback to config
     */
    public function getEnvatoSettings()
    {
        $setting = Setting::first();

        return [
            'token' => $setting->envato_personal_token ?? config('envato.token', env('ENVATO_PERSONAL_TOKEN')),
            'api_key' => $setting->envato_api_key ?? config('envato.api_key'),
            'client_id' => $setting->envato_client_id ?? config('envato.client_id'),
            'client_secret' => $setting->envato_client_secret ?? config('envato.client_secret'),
            'redirect' => $setting->envato_redirect_uri ?? config('services.envato.redirect'),
            'oauth_enabled' => $setting->envato_oauth_enabled ?? false,
            'username' => $setting->envato_username ?? null,
            'auth_enabled' => $setting->envato_auth_enabled ?? false,
        ];
    }

    public function verifyPurchase(string $purchaseCode): ?array
    {
        $settings = $this->getEnvatoSettings();
        $token = $settings['token'];

        if (empty($token)) {
            return null;
        }

        $cacheKey = 'envato_purchase_' . md5($purchaseCode);

        return Cache::remember($cacheKey, now()->addMinutes(30), function () use ($purchaseCode, $token) {
            $response = Http::withToken($token)
                ->acceptJson()
                ->get("{$this->baseUrl}/v3/market/author/sale", [
                    'code' => $purchaseCode,
                ]);

            if ($response->failed()) {
                return null;
            }

            return $response->json();
        });
    }

    public function getUserInfo(string $username): ?array
    {
        $settings = $this->getEnvatoSettings();
        $token = $settings['token'];

        if (empty($token)) {
            return null;
        }

        $cacheKey = 'envato_user_' . md5($username);

        return Cache::remember($cacheKey, now()->addHours(1), function () use ($username, $token) {
            $response = Http::withToken($token)
                ->acceptJson()
                ->get("{$this->baseUrl}/v2/market/user:" . $username);

            if ($response->failed()) {
                return null;
            }

            return $response->json();
        });
    }

    public function getOAuthUserInfo(string $accessToken): ?array
    {
        $cacheKey = 'envato_oauth_user_' . md5($accessToken);

        return Cache::remember($cacheKey, now()->addMinutes(30), function () use ($accessToken) {
            $response = Http::withToken($accessToken)
                ->acceptJson()
                ->get("{$this->baseUrl}/v1/market/private/user/account.json");

            if ($response->failed()) {
                return null;
            }

            return $response->json();
        });
    }

    public function testToken(string $token): bool
    {
        try {
            $response = Http::withToken($token)
                ->acceptJson()
                ->timeout(30)
                ->get("{$this->baseUrl}/v1/market/private/user/account.json");

            return $response->successful();
        } catch (\Exception $e) {
            return false;
        }
    }

    public function getItemInfo(int $itemId): ?array
    {
        $settings = $this->getEnvatoSettings();
        $token = $settings['token'];

        if (empty($token)) {
            return null;
        }

        $cacheKey = 'envato_item_' . $itemId;

        return Cache::remember($cacheKey, now()->addHours(6), function () use ($itemId, $token) {
            $response = Http::withToken($token)
                ->acceptJson()
                ->get("{$this->baseUrl}/v3/market/catalog/item", [
                    'id' => $itemId,
                ]);

            if ($response->failed()) {
                return null;
            }

            return $response->json();
        });
    }

    public function getUserItems(string $username): ?array
    {
        $settings = $this->getEnvatoSettings();
        $token = $settings['token'];

        if (empty($token)) {
            return null;
        }

        $cacheKey = 'envato_user_items_' . md5($username);

        return Cache::remember($cacheKey, now()->addHours(6), function () use ($username, $token) {
            $response = Http::withToken($token)
                ->acceptJson()
                ->get("{$this->baseUrl}/v2/market/user/items-by-author", [
                    'username' => $username,
                ]);

            if ($response->failed()) {
                return null;
            }

            return $response->json();
        });
    }

    public function validateToken(): bool
    {
        $settings = $this->getEnvatoSettings();
        $token = $settings['token'];

        if (empty($token)) {
            return false;
        }

        $response = Http::withToken($token)
            ->acceptJson()
            ->get("{$this->baseUrl}/v1/market/private/user/account.json");

        return $response->successful();
    }

    public function clearCache(): void
    {
        Cache::forget('envato_purchase_*');
        Cache::forget('envato_user_*');
        Cache::forget('envato_item_*');
        Cache::forget('envato_user_items_*');
    }
}

