<?php

declare(strict_types=1);

namespace App\Controller;

use App\Entity\Profile;
use App\Repository\ProfileRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Attribute\Route;

final class SessionProfilesController
{
    public function __construct(
        private readonly ProfileRepository $profiles,
        private readonly EntityManagerInterface $entityManager
    ) {
    }

    #[Route('/api/session/profiles', name: 'api_session_profiles_list', methods: ['GET'])]
    public function list(): JsonResponse
    {
        $items = $this->profiles->createQueryBuilder('p')
            ->andWhere('p.isActive = :active')
            ->setParameter('active', true)
            ->orderBy('p.firstName', 'ASC')
            ->getQuery()
            ->getResult();

        return new JsonResponse(array_map([$this, 'serializeProfile'], $items));
    }

    #[Route('/api/session/profiles', name: 'api_session_profiles_create', methods: ['POST'])]
    public function create(Request $request): JsonResponse
    {
        $payload = $request->toArray();
        $firstName = trim((string) ($payload['firstName'] ?? ''));
        $lastName = trim((string) ($payload['lastName'] ?? ''));

        if ($firstName === '' || $lastName === '') {
            return new JsonResponse(['message' => 'firstName et lastName sont requis.'], JsonResponse::HTTP_BAD_REQUEST);
        }

        $profile = new Profile();
        $profile->setFirstName($firstName);
        $profile->setLastName($lastName);
        $profile->setIsActive(true);

        $this->entityManager->persist($profile);
        $this->entityManager->flush();

        return new JsonResponse($this->serializeProfile($profile), JsonResponse::HTTP_CREATED);
    }

    #[Route('/api/session/profiles/{id}', name: 'api_session_profiles_delete', methods: ['DELETE'])]
    public function delete(string $id): JsonResponse
    {
        $profile = $this->profiles->find($id);
        if (!$profile) {
            return new JsonResponse(['message' => 'Profil introuvable.'], JsonResponse::HTTP_NOT_FOUND);
        }

        $profile->setIsActive(false);
        $this->entityManager->flush();

        return new JsonResponse(['success' => true]);
    }

    private function serializeProfile(Profile $profile): array
    {
        return [
            'id' => $profile->getId(),
            'firstName' => $profile->getFirstName(),
            'lastName' => $profile->getLastName(),
            'isActive' => $profile->isActive(),
        ];
    }
}
