<?php

declare(strict_types=1);

namespace App\Service;

use App\Entity\Installation;
use Doctrine\ORM\EntityManagerInterface;

/**
 * Verifies license with habercms.com.tr API using native curl.
 * Caches result in Installation entity (6-hour interval).
 */
class LicenseVerificationService
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private readonly string $licenseApiUrl,
    ) {}

    public function verify(Installation $installation): bool
    {
        $licenseKey = $installation->getLicenseKey();
        if (!$licenseKey) {
            return false;
        }

        $body = json_encode([
            'license_key' => $licenseKey,
            'domain' => $installation->getDomain(),
        ]);

        $signature = hash_hmac('sha256', $body, $licenseKey);
        $url = rtrim($this->licenseApiUrl, '/') . '/api/license/verify';

        $data = $this->curlPost($url, $body, [
            'Content-Type: application/json',
            'X-HaberCMS-Signature: ' . $signature,
        ]);

        if ($data === null) {
            // API'ye ulaşılamıyorsa mevcut cache'i koru
            return $installation->isLicenseValid();
        }

        // Sonucu Installation'a yaz
        if (($data['valid'] ?? false) === true) {
            $installation->setLicenseStatus('active');
            $installation->setPlan($data['plan'] ?? 'starter');
            $installation->setLicenseExpiresAt(
                isset($data['expires_at']) ? new \DateTimeImmutable($data['expires_at']) : null
            );
        } else {
            $error = $data['error'] ?? 'unknown';
            $installation->setLicenseStatus(
                $error === 'license_expired' ? 'expired' : 'invalid'
            );
        }

        $installation->setLicenseCachedAt(new \DateTimeImmutable());
        $installation->setLicenseCacheJson(json_encode($data));

        $this->entityManager->flush();

        return $installation->isLicenseValid();
    }

    public function heartbeat(Installation $installation): void
    {
        $licenseKey = $installation->getLicenseKey();
        if (!$licenseKey) return;

        $body = json_encode([
            'license_key' => $licenseKey,
            'domain' => $installation->getDomain(),
            'version' => '1.0.0',
        ]);

        $url = rtrim($this->licenseApiUrl, '/') . '/api/license/heartbeat';
        $this->curlPost($url, $body, ['Content-Type: application/json'], 5);
    }

    private function curlPost(string $url, string $body, array $headers, int $timeout = 10): ?array
    {
        $ch = curl_init($url);
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => true,
            CURLOPT_POSTFIELDS => $body,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_TIMEOUT => $timeout,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
        ]);

        $response = curl_exec($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($response === false || $httpCode >= 500) {
            return null;
        }

        return json_decode($response, true) ?: null;
    }
}
