<?php

declare(strict_types=1);

namespace App\Http\Controllers\License;

use App\Domain\License\Exceptions\LicenseClientException;
use App\Domain\License\Services\LicenseManager;
use App\Domain\License\Services\MachineFingerprint;
use App\Domain\License\Services\OnoxsoftLicenseClient;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class ActivateController extends Controller
{
    /**
     * Admin panel'den IP transfer: License Server'a /api/v1/transfer-ip POST eder.
     * Mevcut JWT'den uuid çekilir, yeni IP+machine_id ile bind edilir, yeni JWT cache'lenir.
     */
    public function transferIp(
        Request $request,
        LicenseManager $manager,
        OnoxsoftLicenseClient $client,
        MachineFingerprint $fp,
    ): JsonResponse {
        $claims = $manager->getValidClaims();
        if (! $claims) {
            return response()->json(['error' => 'no_active_license'], 422);
        }

        $licenseUuid = $claims['sub'] ?? '';
        if (! $licenseUuid) {
            return response()->json(['error' => 'invalid_jwt'], 422);
        }

        $newIp = $fp->publicIp();

        try {
            $result = $client->transferIp($licenseUuid, [
                'new_ip' => $newIp,
                'new_machine_id' => $fp->machineId(),
                'new_hostname' => $fp->hostname(),
            ]);

            $manager->storeJwt($result['jwt']);

            Log::info('License IP transferred', [
                'uuid' => $licenseUuid,
                'new_ip' => $newIp,
                'new_mid' => $fp->machineId(),
            ]);

            return response()->json([
                'message' => 'IP başarıyla aktarıldı',
                'tier' => $result['claims']['license']['tier'] ?? null,
                'bound_ip' => $result['claims']['license']['bound_ip'] ?? null,
            ]);
        } catch (LicenseClientException $e) {
            Log::warning('License IP transfer failed', [
                'uuid' => $licenseUuid,
                'error' => $e->getMessage(),
            ]);

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