<?php

namespace App\Security;

use App\Entity\User;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;

final class ParentLoginSuccessHandler implements AuthenticationSuccessHandlerInterface
{
    public function onAuthenticationSuccess(Request $request, TokenInterface $token): JsonResponse
    {
        $user = $token->getUser();

        if (!$user instanceof User) {
            return new JsonResponse(['error' => 'invalid_parent'], 401);
        }

        $request->getSession()->migrate(true);

        return new JsonResponse([
            'id' => $user->getId(),
            'displayName' => $user->getDisplayName(),
            'family' => [
                'id' => $user->getFamily()->getId(),
                'name' => $user->getFamily()->getName(),
                'timezone' => $user->getFamily()->getTimezone(),
            ],
        ]);
    }
}
