<?php

namespace App\Licensing\Services;

use App\Installer\Services\DomainResolver;
use App\Installer\Services\LicenseStorage;
use Exception;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

/**
 * License Service (LixServ)
 * Handles license management, caching, and storage
 */
class LixServ
{
    /**
     * License API endpoint
     */
    private const LICENSE_API_URL = 'https://api.matheme.app/api/license';

    /**
     * Cache key prefix
     */
    private const CACHE_PREFIX = 'license_';

    /**
     * Cache duration in minutes (24 hours)
     */
    private const CACHE_DURATION = 1440;

    public function __construct(
        private LicenseStorage $licenseStorage,
        private DomainResolver $domainResolver
    ) {}

    /**
     * Get license information
     */
    public function getLicenseInfo(): ?array
    {
        return $this->licenseStorage->get();
    }

    /**
     * Check if license exists
     */
    public function hasLicense(): bool
    {
        return $this->licenseStorage->exists();
    }

    /**
     * Get license code (decrypted)
     */
    public function getLicenseCode(): ?string
    {
        $licenseInfo = $this->getLicenseInfo();

        if (! $licenseInfo || ! isset($licenseInfo['license_code'])) {
            return null;
        }

        try {
            return decrypt($licenseInfo['license_code']);
        } catch (Exception $e) {
            Log::error('License decryption failed: '.$e->getMessage());

            return null;
        }
    }

    /**
     * Get license email (decrypted)
     */
    public function getLicenseEmail(): ?string
    {
        $licenseInfo = $this->getLicenseInfo();

        if (! $licenseInfo || ! isset($licenseInfo['email'])) {
            return null;
        }

        try {
            return decrypt($licenseInfo['email']);
        } catch (Exception $e) {
            Log::error('Email decryption failed: '.$e->getMessage());

            return null;
        }
    }

    /**
     * Get license domain
     */
    public function getLicenseDomain(): ?string
    {
        $licenseInfo = $this->getLicenseInfo();

        return $licenseInfo['domain'] ?? null;
    }

    /**
     * Get current installation domain
     */
    public function getCurrentDomain(): string
    {
        return $this->domainResolver->getInstallationDomain();
    }

    /**
     * Check if domain matches license
     */
    public function isDomainValid(): bool
    {
        $licenseDomain = $this->getLicenseDomain();
        $currentDomain = $this->getCurrentDomain();

        if (! $licenseDomain) {
            return false;
        }

        // Normalize domains for comparison
        $licenseDomain = strtolower(trim($licenseDomain));
        $currentDomain = strtolower(trim($currentDomain));

        return $licenseDomain === $currentDomain;
    }

    /**
     * Get cached license status
     */
    public function getCachedStatus(): ?array
    {
        $cacheKey = self::CACHE_PREFIX.'status';

        return Cache::get($cacheKey);
    }

    /**
     * Cache license status
     */
    public function cacheStatus(array $status): void
    {
        $cacheKey = self::CACHE_PREFIX.'status';
        Cache::put($cacheKey, $status, now()->addMinutes(self::CACHE_DURATION));
    }

    /**
     * Clear license cache
     */
    public function clearCache(): void
    {
        $cacheKey = self::CACHE_PREFIX.'status';
        Cache::forget($cacheKey);
    }

    /**
     * Get product ID
     */
    public function getProductId(): string
    {
        return 'proinvoice';
    }
}
