<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Device;
use Illuminate\Http\JsonResponse;

class DeviceApiController extends Controller
{
    /**
     * Return device configuration as JSON for ESP32.
     *
     * GET /api/device
     */
    public function show(): JsonResponse
    {
        $device = Device::sole();

        return response()->json([
            'name'       => $device->name,
            'goal'       => $device->goal,
            'weather'    => $device->weather,
            'quote'      => $device->quote,
            'brightness' => $device->brightness,
            'animation'  => $device->animation,
            'refresh'    => $device->refresh,
        ]);
    }

    /**
     * Allow ESP32 to POST its status (heartbeat).
     *
     * POST /api/device/heartbeat
     */
    public function heartbeat(\Illuminate\Http\Request $request): JsonResponse
    {
        $validated = $request->validate([
            'ip'               => ['nullable', 'string', 'max:45'],
            'wifi_strength'    => ['nullable', 'integer'],
            'firmware_version' => ['nullable', 'string', 'max:20'],
        ]);

        $device = Device::sole();
        $device->update([
            'current_ip'       => $validated['ip'] ?? $request->ip(),
            'wifi_strength'    => $validated['wifi_strength'] ?? $device->wifi_strength,
            'firmware_version' => $validated['firmware_version'] ?? $device->firmware_version,
            'last_seen'        => now(),
        ]);

        return response()->json(['status' => 'ok', 'ts' => now()->toISOString()]);
    }
}
