<?php

declare(strict_types=1);

namespace App\Http\Controllers\License;

use App\Domain\License\Exceptions\LicenseClientException;
use App\Domain\License\Services\KillSwitch;
use App\Domain\License\Services\LicenseManager;
use App\Domain\License\Services\MachineFingerprint;
use App\Domain\License\Services\OnoxsoftLicenseClient;
use App\Domain\License\Services\PurchaseIntentBuilder;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response;

/**
 * BuyController — /lisans/satin-al sayfası (Panel-Side).
 *
 * Lisans yokken müşterinin tek erişilebilir sayfası. Mevcut sunucu fingerprint'ini
 * gösterir, plan seçtirir, License Server'a yönlendirir, sonra polling ile aktive
 * olduğunda otomatik panel'e döner.
 *
 * EnforceLicense middleware bu route'lara izin veriyor — KillSwitch aktifken bile
 * erişilebilir.
 */
class BuyController extends Controller
{
    public function __construct(
        private LicenseManager $manager,
        private MachineFingerprint $fp,
        private PurchaseIntentBuilder $builder,
        private OnoxsoftLicenseClient $client,
        private KillSwitch $killSwitch,
    ) {}

    public function show(Request $request): Response
    {
        $licenseInfo = null;
        if ($this->manager->isValid()) {
            $licenseInfo = [
                'tier' => $this->manager->tier(),
                'expires_at' => $this->manager->expiresAt()?->toIso8601String(),
                'account_limit' => $this->manager->accountLimit() === PHP_INT_MAX
                    ? null
                    : $this->manager->accountLimit(),
            ];
        }

        return Inertia::render('License/Buy', [
            'current_license' => $licenseInfo,
            'kill_switch_active' => $this->killSwitch->isActive(),
            'kill_switch_reason' => $this->killSwitch->lastReason(),
            'fingerprint' => [
                'ip' => $this->fp->publicIp(),
                'hostname' => $this->fp->hostname(),
                'machine_id' => $this->fp->machineId(),
            ],
            'server_url' => config('onoxsoft.server.base_url', 'https://onox.com.tr'),
        ]);
    }

    public function generateIntent(Request $request): RedirectResponse
    {
        $ip = $this->fp->publicIp();
        $token = $this->builder->build(
            ip: $ip,
            hostname: $this->fp->hostname(),
            panelVersion: (string) config('app.version', '1.0.0'),
            ttlSeconds: 3600,
        );

        // Polling için intent token'ı session'a kaydet
        session(['onoxsoft.pending_intent' => $token]);

        $buyUrl = rtrim((string) config('onoxsoft.server.base_url', 'https://onox.com.tr'), '/')
            .'/buy?intent='.$token;

        return redirect()->away($buyUrl);
    }

    public function poll(Request $request): JsonResponse
    {
        $token = session('onoxsoft.pending_intent');
        if (! $token) {
            return response()->json(['status' => 'no_pending_intent'], 404);
        }

        try {
            $result = $this->client->checkIntent($token);
            $status = $result['status'] ?? 'unknown';

            // License hazır — activate çağır
            if ($status === 'ready_to_activate') {
                $ip = $this->fp->publicIp();
                $activated = $this->client->activate([
                    'intent_token' => $token,
                    'ip' => $ip,
                    'machine_id' => $this->fp->machineId(),
                    'hostname' => $this->fp->hostname(),
                    'panel_version' => (string) config('app.version', '1.0.0'),
                ]);

                $this->manager->storeJwt($activated['jwt']);
                session()->forget('onoxsoft.pending_intent');

                return response()->json([
                    'status' => 'activated',
                    'tier' => $activated['claims']['license']['tier'] ?? null,
                ]);
            }

            return response()->json(['status' => $status]);
        } catch (LicenseClientException $e) {
            return response()->json([
                'status' => 'error',
                'message' => $e->getMessage(),
            ], 502);
        }
    }
}
