<?php

namespace App\Services;

use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Str;

class DiintaLicenseClient
{
    protected string $productCode;
    protected string $apiUrl;

    public function __construct(string $productCode, string $apiUrl = 'https://diinta.so/api/v1/public')
    {
        $this->productCode = $productCode;
        $this->apiUrl = rtrim($apiUrl, '/');
    }

    public function verify(string $licenseKey, ?string $domain = null): bool
    {
        $cacheKey = 'diinta_lic_' . md5($this->productCode . $licenseKey);

        return Cache::remember($cacheKey, now()->addHours(24), function () use ($licenseKey, $domain) {
            $response = Http::timeout(10)->post("{$this->apiUrl}/licenses/verify", [
                'product_code' => $this->productCode,
                'license_key'  => trim($licenseKey),
                'domain'       => $domain ?: request()->getHost(),
                'instance_id'  => config('app.instance_uuid', config('app.key')),
            ]);

            return $response->successful() && $response->json('ok') === true;
        });
    }

    public function activate(string $licenseKey, ?string $domain = null): array
    {
        $response = Http::timeout(12)->post("{$this->apiUrl}/licenses/activate", [
            'product_code' => $this->productCode,
            'license_key'  => trim($licenseKey),
            'domain'       => $domain ?: request()->getHost(),
            'instance_id'  => config('app.instance_uuid', config('app.key')),
        ]);

        return $response->json() ?? ['ok' => false, 'message' => 'Connection failed'];
    }
}