<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\AgentRegisterRequest;
use App\Models\Device;
use App\Support\PairingCode;
use Illuminate\Http\JsonResponse;

class AgentController extends Controller
{
    public function register(AgentRegisterRequest $request): JsonResponse
    {
        $token = bin2hex(random_bytes(32));
        $code = $this->generateUniquePairingCode();

        $device = Device::create([
            'name' => $request->string('hostname')->toString(),
            'hostname' => $request->string('hostname'),
            'os_info' => $request->string('os_info'),
            'local_ip' => $request->string('local_ip'),
            'pairing_code' => $code,
            'pairing_expires_at' => now()->addMinutes(10),
            'device_token_hash' => hash('sha256', $token),
        ]);

        return response()->json([
            'pairing_code' => $code,
            'device_token' => $token,
            'expires_at' => $device->pairing_expires_at->toIso8601String(),
        ], 201);
    }

    public function heartbeat(\Illuminate\Http\Request $request): JsonResponse
    {
        $device = $request->attributes->get('device');

        $device->update([
            'online' => true,
            'last_seen_at' => now(),
            'last_ip' => $request->ip(),
        ]);

        return response()->json([
            'claimed' => $device->user_id !== null,
            'name' => $device->name,
        ]);
    }

    private function generateUniquePairingCode(): string
    {
        do {
            $code = PairingCode::generate();
        } while (Device::where('pairing_code', $code)->exists());
        return $code;
    }
}
