﻿<?php

namespace App\Support;

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

class OvionLicenseClient
{
    public function __construct(
        private readonly string $apiBase,
        private readonly string $licenseKey,
        private readonly string $productSlug,
        private readonly string $productVersion,
    ) {}

    public function activate(): array
    {
        return $this->post('/api/licenses/activate');
    }

    public function deactivate(): array
    {
        Cache::forget($this->cacheKey());

        return $this->post('/api/licenses/deactivate');
    }

    public function check(bool $force = false): array
    {
        if ($force) {
            Cache::forget($this->cacheKey());
        }

        return Cache::remember($this->cacheKey(), now()->addDay(), fn () => $this->post('/api/licenses/check'));
    }

    public function updateCheck(): array
    {
        return $this->post('/api/licenses/update-check');
    }

    private function post(string $path): array
    {
        if (trim($this->licenseKey) === '') {
            return ['valid' => false, 'status' => 'missing', 'message' => 'Enter a license key.'];
        }

        $response = Http::acceptJson()
            ->timeout(15)
            ->post(rtrim($this->apiBase, '/').$path, $this->payload());

        return $response->json() ?: ['valid' => false, 'status' => 'invalid_response', 'message' => 'Invalid license server response.'];
    }

    private function payload(): array
    {
        return [
            'license_key' => $this->licenseKey,
            'product_slug' => $this->productSlug,
            'product_version' => $this->productVersion,
            'site_url' => config('app.url'),
            'domain' => parse_url((string) config('app.url'), PHP_URL_HOST),
            'installation_uuid' => $this->installationUuid(),
            'environment' => app()->environment('production') ? 'production' : 'development',
            'client' => 'laravel',
        ];
    }

    private function installationUuid(): string
    {
        $path = storage_path('app/ovion-installation-id');
        if (! is_file($path)) {
            file_put_contents($path, (string) Str::uuid());
        }

        return trim((string) file_get_contents($path));
    }

    private function cacheKey(): string
    {
        return 'ovion_license_'.sha1($this->productSlug.'|'.$this->licenseKey);
    }
}
