<?php

namespace App\Controller;

use App\Entity\Device;
use App\Repository\ChildRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Attribute\Route;

final class DeviceBootstrapController extends AbstractController
{
    public function __construct(private readonly ChildRepository $children)
    {
    }

    #[Route('/api/v1/device/bootstrap', name: 'api_device_bootstrap', methods: ['GET'])]
    public function __invoke(): JsonResponse
    {
        $device = $this->getUser();
        if (!$device instanceof Device) {
            throw $this->createAccessDeniedException();
        }

        $family = $device->getFamily();

        return new JsonResponse([
            'device' => [
                'id' => $device->getId(),
                'label' => $device->getLabel(),
            ],
            'family' => [
                'id' => $family->getId(),
                'name' => $family->getName(),
                'timezone' => $family->getTimezone(),
            ],
            'children' => array_map(static fn ($child) => [
                'id' => $child->getId(),
                'firstName' => $child->getFirstName(),
            ], $this->children->findActiveForFamily($family)),
        ]);
    }
}
