<?php

namespace Modules\PortalApi\Http\Controllers\Api;

use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Modules\PortalApi\Entities\PortalOwner;
use Modules\PortalApi\Entities\PortalOwnerDevice;

class PortalDeviceController extends Controller
{
    /**
     * PWA pings this on every boot.
     * Body: { "installed": boolean }   ← from window.matchMedia('(display-mode: standalone)').matches
     * Returns the current device row so the PWA can stop pinging if not needed.
     */
    public function ping(Request $request): JsonResponse
    {
        $data = $request->validate([
            'installed' => 'nullable|boolean',
        ]);
        $owner = $request->attributes->get('portal_owner');
        if (! $owner instanceof PortalOwner) {
            // demo-* tokens have no real owner — no-op (200 so PWA doesn't retry).
            return response()->json(['ok' => true]);
        }
        $device = PortalOwnerDevice::ping(
            $owner->id,
            $request,
            (bool) ($data['installed'] ?? false)
        );
        return response()->json([
            'installed_at' => $device->installed_at?->toIso8601String(),
            'platform'     => $device->platform,
        ]);
    }
}
