<?php

namespace App\Models;

use App\Services\MarketplaceService;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class MarketplacePurchase extends Model
{
    protected $fillable = ['item_type', 'item_slug', 'license_key', 'stripe_checkout_session_id', 'is_active', 'admin_enabled', 'purchased_at'];

    protected $casts = [
        'purchased_at' => 'datetime',
        'is_active' => 'boolean',
        'admin_enabled' => 'boolean',
    ];

    public static function hasPurchased(string $type, string $slug): bool
    {
        if ($type === 'plugin' && $slug === 'multilang' && env('MULTILANG_FORCE_ACTIVE', false)) {
            return true;
        }
        if ($type === 'plugin' && $slug === 'captcha-protection' && env('CAPTCHA_PROTECTION_FORCE_ACTIVE', false)) {
            return true;
        }
        $purchase = static::where('item_type', $type)
            ->where('item_slug', $slug)
            ->where('is_active', true)
            ->first();

        if (! $purchase) {
            return false;
        }

        // Toggle admin (Activer / Désactiver) — distinct de is_active (révocation licence serveur)
        if (! ($purchase->admin_enabled ?? true)) {
            return false;
        }

        // Validation serveur obligatoire pour les plugins (toutes les clés, y compris STRIPE-xxx en attente)
        if ($type === 'plugin') {
            $cacheKey = 'license_valid_'.$purchase->license_key.'_'.$slug;
            $valid = Cache::remember($cacheKey, now()->addHours(72), function () use ($purchase, $slug) {
                return app(MarketplaceService::class)->validateLicense($slug, $purchase->license_key);
            });
            if (! $valid) {
                $purchase->update(['is_active' => false]);
                Cache::forget($cacheKey);
                return false;
            }
        }

        return true;
    }
}
