<?php

declare(strict_types=1);

namespace App\Controller;

use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[Route('/api/user')]
#[IsGranted('ROLE_USER')]
class UserApiController extends AbstractController
{
    private const VALID_THEMES = [
        'warm-craft',
        'playful-pop',
        'sage-cream',
        'dusty-mauve',
        'ocean-dusk',
        'honey-slate',
    ];

    #[Route('/theme', name: 'api_user_theme', methods: ['PATCH'])]
    public function updateTheme(Request $request, EntityManagerInterface $em): JsonResponse
    {
        $body = json_decode($request->getContent(), true);
        $theme = $body['theme'] ?? null;

        if (!is_string($theme) || !in_array($theme, self::VALID_THEMES, true)) {
            return $this->json(['error' => 'Invalid theme'], Response::HTTP_UNPROCESSABLE_ENTITY);
        }

        /** @var User $user */
        $user = $this->getUser();
        $user->setTheme($theme);
        $em->flush();

        return $this->json(['theme' => $theme]);
    }
}
