<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class MarketplaceService
{
    /**
     * Hôte utilisé pour la licence : navigateur en priorité (évite localhost vs 127.0.0.1 selon APP_URL).
     */
    public function licenseDomainForRequest(): string
    {
        if (! app()->runningInConsole()) {
            try {
                $h = request()->getHost();
                if (is_string($h) && $h !== '') {
                    return strtolower(trim($h));
                }
            } catch (\Throwable) {
                // pas de requête HTTP
            }
        }

        $fromApp = parse_url((string) config('app.url'), PHP_URL_HOST);

        return strtolower(trim(is_string($fromApp) && $fromApp !== '' ? $fromApp : 'localhost'));
    }

    public function validateLicense(string $pluginSlug, string $licenseKey, ?string $domain = null): bool
    {
        $url = rtrim(config('marketplace.license.url', ''), '/').'/api/validate-license';
        if (empty($url) || empty(config('marketplace.license.api_key'))) {
            return false;
        }
        $domain = $domain ?? $this->licenseDomainForRequest();
        $response = Http::timeout(10)->withHeaders([
            'Authorization' => 'Bearer '.config('marketplace.license.api_key'),
        ])->post($url, [
            'license_key' => $licenseKey,
            'plugin_slug' => $pluginSlug,
            'domain' => $domain,
        ]);

        return $response->successful() && ($response->json('valid') ?? false);
    }

    public function getLicenseFromSession(string $sessionId, string $itemType, string $itemSlug): ?array
    {
        $url = rtrim(config('marketplace.license.url', ''), '/').'/api/licenses/from-session';
        if (empty($url) || empty(config('marketplace.license.api_key'))) {
            return null;
        }
        $domain = $this->licenseDomainForRequest();
        $response = Http::timeout(15)->withHeaders([
            'Authorization' => 'Bearer '.config('marketplace.license.api_key'),
        ])->post($url, [
            'session_id' => $sessionId,
            'item_type' => $itemType,
            'item_slug' => $itemSlug,
            'domain' => $domain,
        ]);
        if (! $response->successful()) {
            return null;
        }

        return $response->json();
    }
}
