<?php

namespace App\Http\Controllers\AiPortal;

use App\Services\AuditLogger;
use App\Services\Whmcs\WhmcsClient;
use App\Services\Whmcs\WhmcsConnection;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;

class WhmcsConnectionController extends Controller
{
    public function show(Request $request, WhmcsConnection $conn)
    {
        abort_unless($request->user()->isAdminOrAbove(), 403);
        return response()->json($conn->safe());
    }

    public function update(Request $request, WhmcsConnection $conn)
    {
        abort_unless($request->user()->isAdminOrAbove(), 403);

        $data = $request->validate([
            'url'                     => ['nullable', 'url', 'max:255'],
            // Empty = "leave existing untouched", per masked-display flow.
            'identifier'              => ['nullable', 'string', 'max:255'],
            'secret'                  => ['nullable', 'string', 'max:255'],
            'investigation_enabled'   => ['nullable', 'boolean'],
            'investigation_dept_ids'  => ['nullable', 'string', 'max:128'],
            'ssl_verify'              => ['nullable', 'boolean'],
        ]);

        $saved = $conn->set($data);

        AuditLogger::log('user', (string) $request->user()->id, $request->user()->email,
            'whmcs.connection_updated', 'whmcs', 'connection',
            ['url_changed' => array_key_exists('url', $data),
             'secret_rotated' => ! empty($data['secret']),
             'identifier_rotated' => ! empty($data['identifier'])], $request);

        return response()->json($saved);
    }

    /**
     * Live-test the configured connection by hitting WHMCS GetActivityLog
     * (cheap, read-only, always available). Records the result on the
     * settings row so the UI can show last-tested status.
     */
    public function test(Request $request, WhmcsConnection $conn)
    {
        abort_unless($request->user()->isAdminOrAbove(), 403);

        // Fresh-from-DB client picks up any unsaved-but-just-saved values.
        $client = app(WhmcsClient::class);
        if (! $client->isConfigured()) {
            $conn->recordTestResult(false, 'Not configured — set URL, identifier, secret first');
            return response()->json(['ok' => false, 'msg' => 'Not configured. Set URL, identifier and secret first.']);
        }

        $start = microtime(true);
        $r = $client->call('GetActivityLog', ['limitnum' => 1]);
        $latency = (int) ((microtime(true) - $start) * 1000);

        $ok  = $r && ($r['result'] ?? '') === 'success';
        $msg = $ok
            ? "Reached WHMCS · " . ($r['totalresults'] ?? 0) . " activity rows accessible · {$latency}ms"
            : 'WHMCS rejected: ' . ($r['message'] ?? 'no response');

        $conn->recordTestResult($ok, $msg);

        AuditLogger::log('user', (string) $request->user()->id, $request->user()->email,
            'whmcs.connection_tested', 'whmcs', 'connection',
            ['ok' => $ok, 'latency_ms' => $latency], $request);

        return response()->json([
            'ok'         => $ok,
            'msg'        => $msg,
            'latency_ms' => $latency,
            'connection' => $conn->safe(),
        ]);
    }
}
