<?php

namespace App\Http\Controllers\Admin;

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

/**
 * PROCP lisans SİSTEMİ yönetim/durum sayfası (PRC-873, Slice B).
 *
 * (PRC-60 License modül ailesinin LicenseController'ından AYRI — o ClientLicense
 * resale'i yönetir; bu, PROCP'nin kendi lisans doğrulama sistemidir — PRC-868.)
 *
 * İki katmanlı/özyinelemeli model için turnkey yüzey:
 *  - Bu instance'ın lisans durumu (mode, status, expiry) — LicenseService::state().
 *  - Upstream `server_url` + mode admin'den yapılandırılır (DB ayarı, env fallback;
 *    white-label reseller .env düzenlemeden).
 *  - Alt-müşterilere verilecek DOWNSTREAM endpoint URL'i gösterilir (özyineleme).
 */
class SystemLicenseController extends Controller
{
    public function index(LicenseService $license)
    {
        return view('admin.system.license.index', [
            'state' => $license->state(),
            'mode' => Setting::getValue('license_mode') ?: config('license.mode', 'self'),
            'serverUrl' => Setting::getValue('license_server_url') ?: config('license.server_url', ''),
            'keyMasked' => $this->maskKey((string) config('license.key', '')),
            'downstream' => $license->downstreamEndpoint(),
        ]);
    }

    public function update(Request $request)
    {
        $data = $request->validate([
            'mode' => ['required', 'in:self,client'],
            'server_url' => ['nullable', 'url', 'max:255'],
        ]);

        if ($data['mode'] === 'client' && empty($data['server_url'])) {
            return back()->with('error', __('admin/license.err_server_required'));
        }

        Setting::set('license_mode', $data['mode']);
        Setting::set('license_server_url', rtrim((string) ($data['server_url'] ?? ''), '/'));

        return back()->with('success', __('admin/license.saved'));
    }

    /** Upstream lisans sunucusuna canlı doğrulama denemesi. */
    public function test(LicenseService $license)
    {
        $fresh = $license->refresh();
        if ($fresh === null) {
            return back()->with('error', __('admin/license.test_unreachable'));
        }

        $payload = (array) ($fresh['payload'] ?? []);
        if (! empty($payload['valid'])) {
            return back()->with('success', __('admin/license.test_valid', ['status' => $payload['status'] ?? 'active']));
        }

        return back()->with('error', __('admin/license.test_invalid', ['status' => $payload['status'] ?? 'invalid']));
    }

    private function maskKey(string $key): string
    {
        return $key === '' ? '—' : \Illuminate\Support\Str::mask($key, '*', 6);
    }
}
