<?php

namespace App\Http\Controllers;

use App\Services\AuditLogger;
use App\Services\License;
use App\Services\Settings;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Inertia\Inertia;
use Inertia\Response as InertiaResponse;

class LicenseController extends Controller
{
    /**
     * The standalone activation screen. Reachable even when unlicensed
     * (EnforceLicense allowlists the license.* routes).
     */
    public function verify(Request $request): InertiaResponse
    {
        return Inertia::render('License/Verify', [
            'itemId' => config('license.item_id'),
            'productUrl' => config('license.product_url'),
            'currentDomain' => $request->getHost(),
            'status' => Settings::get('license.status'),
            'domain' => Settings::get('license.domain'),
            'supportedUntil' => Settings::get('license.supported_until'),
            'error' => session('error'),
        ]);
    }

    /**
     * Activate a purchase code. On success unlocks the app and redirects home;
     * on failure returns to the screen with the server's error message.
     */
    public function activate(Request $request): InertiaResponse|RedirectResponse
    {
        $validated = $request->validate([
            'purchase_code' => ['required', 'string', 'min:10', 'max:64'],
            'email' => ['required', 'email', 'max:190'],
            'consent' => ['sometimes', 'boolean'],
        ]);

        // On a dev host the app is already unlocked (EnforceLicense bypasses it),
        // and the verify server rubber-stamps ANY code from a localhost/dev
        // domain — so "activating" here is meaningless and would persist a bogus
        // `status=active` that could mislead a later production deploy. Refuse,
        // and tell the user to activate on the live domain. (You can't truly
        // test verification locally anyway — the server can't validate a dev
        // domain; use the real domain.)
        if (License::isBypassed($request->getHost())) {
            return back()->with('error', 'This is a development host, where licensing is bypassed — activation isn\'t needed (and can\'t be validated here). Activate on your live domain.');
        }

        $result = License::verify(
            $validated['purchase_code'],
            $validated['email'],
            $request->getHost(),
            (bool) ($validated['consent'] ?? false),
        );

        if ($result['ok']) {
            AuditLogger::record('license.activated', null, 'License activated', [
                'domain' => $request->getHost(),
            ]);

            return redirect('/');
        }

        return back()->with('error', $result['message'] ?? 'That purchase code could not be verified.');
    }
}
