<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Models\License;
use App\Services\LicenseKeyGeneratorService;
use Illuminate\Http\Request;

class LicenseController extends Controller
{
    public function verify(Request $request)
    {
        $request->validate([
            'license_key' => 'required|string',
            'domain'      => 'required|string',
            'ip'          => 'required|ip',
        ]);

        $key = $request->license_key;
        $domain = $request->domain;
        $ip = $request->ip();

        $generator = app(LicenseKeyGeneratorService::class);

        // Step 1: Basic format check
        if (! $generator->isValidFormat($key)) {
            return $this->fail('Invalid license format.');
        }

        // Step 2: Lookup license
        $license = License::with('order.subscription')
            ->where('license_key', $key)
            ->first();

        if (! $license) {
            return $this->fail('License not found.', 404);
        }

        if ($license->is_revoked) {
            return $this->fail('License has been revoked.');
        }

        if ($license->isExpired()) {
            return $this->fail('License expired.');
        }

        $domainAllowed = false;
        $ipAllowed = false;

        // Check if explicitly allowed (or if arrays are empty, meaning unrestricted)
        if (empty($license->allowed_domains) || in_array($domain, $license->allowed_domains, true)) {
            $domainAllowed = true;
        }

        if (empty($license->allowed_ips) || in_array($ip, $license->allowed_ips, true)) {
            $ipAllowed = true;
        }

        // Auto-Activation Logic
        $needsUpdate = false;
        if (!$domainAllowed || !$ipAllowed) {
            // Check if we can activate a new instance
            if ($license->max_activations > 0 && $license->activation_count >= $license->max_activations) {
                return $this->fail('Max activations exceeded or unrecognized environment.');
            }

            // We have room for activation. Let's add the domain/IP to the allowed lists
            $allowedDomains = $license->allowed_domains ?? [];
            if (!$domainAllowed && !in_array($domain, $allowedDomains, true)) {
                $allowedDomains[] = $domain;
                $license->allowed_domains = $allowedDomains;
                $needsUpdate = true;
            }

            $allowedIps = $license->allowed_ips ?? [];
            if (!$ipAllowed && !in_array($ip, $allowedIps, true)) {
                $allowedIps[] = $ip;
                $license->allowed_ips = $allowedIps;
                $needsUpdate = true;
            }
            
            if ($needsUpdate) {
                $license->activation_count = $license->activation_count + 1;
                $license->save();
            }
        }

        // ✅ All checks passed
        $isLifetime = is_null($license->expiry_date);
        return response()->json([
            'valid'   => true,
            'product' => $license->product_name ?? null,
            'expiry'  => $isLifetime ? null : $license->expiry_date,
            'lifetime' => $isLifetime,
        ]);
    }

    /**
     * Return standard error response.
     */
    protected function fail(string $reason, int $code = 403)
    {
        return response()->json([
            'valid'  => false,
            'reason' => $reason,
        ], $code);
    }
}
