<?php

namespace App\Http\Controllers\Api;

use App\Http\Concerns\DerivesInstallBaseUrl;
use App\Http\Controllers\Controller;
use App\Models\ActivityLog;
use App\Models\RegistrationToken;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

/**
 * Used by the dashboard's "Add Host" wizard. The admin clicks the button,
 * the SPA POSTs here, we return a token that's valid for 60 minutes. The
 * admin pastes the install command (containing the token) into the target
 * server's terminal, and the agent's installer redeems it for an
 * agent_secret on first contact.
 */
class RegistrationTokenController extends Controller
{
    use DerivesInstallBaseUrl;

    public function store(Request $request): JsonResponse
    {
        abort_unless($request->user()->canManageServers(), 403);

        $data = $request->validate([
            'label' => ['nullable', 'string', 'max:128'],
            'tags' => ['nullable', 'array'],
            'tags.*' => ['string', 'max:64'],
            'expires_in_minutes' => ['nullable', 'integer', 'min:5', 'max:1440'],
        ]);

        $token = RegistrationToken::generate(
            userId: $request->user()->id,
            label: $data['label'] ?? null,
            tags: $data['tags'] ?? [],
            expiresInMinutes: $data['expires_in_minutes'] ?? 60
        );

        ActivityLog::log([
            'action' => 'created registration token',
            'target' => $token->label ?? "token #{$token->id}",
            'category' => 'server',
            'severity' => 'medium',
        ]);

        $base = $this->installBaseUrl($request);

        return response()->json([
            'token' => $token->token,
            'expires_at' => $token->expires_at->toIso8601String(),
            'install_commands' => [
                'linux' => "curl -fsSL {$base}/install.sh | sudo bash -s -- --token {$token->token} --backend {$base}",
                'windows' => "iwr -useb {$base}/install.ps1 -OutFile install.ps1; .\\install.ps1 -Token \"{$token->token}\" -Backend \"{$base}\"",
                'macos' => "curl -fsSL {$base}/install-macos.sh | sudo bash -s -- --token {$token->token} --backend {$base}",
            ],
        ], 201);
    }
}
