<?php

namespace App\Console\Commands;

use App\Models\MarketplacePurchase;
use App\Services\MarketplaceService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;

class TestLicenseServerCommand extends Command
{
    protected $signature = 'license:test
                            {--plugin= : Slug du plugin à tester (ex: section-plus)}
                            {--clear-cache : Vider le cache des licences avant le test}';

    protected $description = 'Tester la connexion au serveur de licence et la validation des plugins';

    public function handle(MarketplaceService $marketplaceService): int
    {
        $url = config('marketplace.license.url');
        $apiKey = config('marketplace.license.api_key');
        $this->info('=== Test du serveur de licence ===');
        $this->newLine();

        $this->table(
            ['Paramètre', 'Valeur'],
            [
                ['URL serveur', $url ?: '(vide)'],
                ['Clé API configurée', $apiKey ? 'Oui' : 'Non'],
                ['Validation serveur (plugins)', 'Toujours active'],
            ]
        );

        if (empty($url) || empty($apiKey)) {
            $this->error('Clé / URL serveur de licence absente : config/gcms.php ($gcmsEmbeddedLicenseApiKey), bootstrap/gcms-infrastructure.key, ou GCMS_DEV_INFRASTRUCTURE + MARKETPLACE_LICENSE_API_KEY.');

            return 1;
        }

        if ($this->option('clear-cache')) {
            foreach (MarketplacePurchase::where('item_type', 'plugin')->get() as $p) {
                Cache::forget('license_valid_'.$p->license_key.'_'.$p->item_slug);
            }
            $this->info('Cache des licences vidé.');
            $this->newLine();
        }

        $pluginSlug = $this->option('plugin');
        $purchases = $pluginSlug
            ? MarketplacePurchase::where('item_type', 'plugin')->where('item_slug', $pluginSlug)->get()
            : MarketplacePurchase::where('item_type', 'plugin')->get();

        foreach ($purchases as $purchase) {
            $domain = $marketplaceService->licenseDomainForRequest();

            $this->line("Plugin: <fg=cyan>{$purchase->item_slug}</> | Clé: ".substr($purchase->license_key, 0, 20).'... | Domaine: <fg=yellow>'.$domain.'</>');

            $valid = $marketplaceService->validateLicense($purchase->item_slug, $purchase->license_key, $domain);
            $this->line($valid
                ? '  → <fg=green>Validé par le serveur</>'
                : '  → <fg=red>Refusé par le serveur (licence invalide ou révoquée)</>');
        }

        $this->newLine();
        $this->info('Pour révoquer une licence : sur le serveur, php artisan license:revoke {clé}');

        return 0;
    }
}
