<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\MainBundle\Controller;

use Chill\MainBundle\CRUD\Controller\ApiController;
use Chill\MainBundle\Pagination\PaginatorInterface;
use Chill\MainBundle\Security\ChillSecurity;
use Doctrine\ORM\QueryBuilder;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\Annotation\Route;

class UserApiController extends ApiController
{
    public function __construct(private readonly ChillSecurity $security) {}

    #[Route(path: '/api/1.0/main/user-current-location.{_format}', name: 'chill_main_user_current_location', requirements: ['_format' => 'json'])]
    public function currentLocation(mixed $_format): JsonResponse
    {
        if (!$this->isGranted('ROLE_USER')) {
            throw new AccessDeniedHttpException();
        }

        return $this->json(
            $this->security->getUser()->getCurrentLocation(),
            JsonResponse::HTTP_OK,
            [],
            ['groups' => ['read']]
        );
    }

    #[Route(path: '/api/1.0/main/whoami.{_format}', name: 'chill_main_user_whoami', requirements: ['_format' => 'json'])]
    public function whoami(mixed $_format): JsonResponse
    {
        return $this->json(
            $this->getUser(),
            JsonResponse::HTTP_OK,
            [],
            ['groups' => ['read']]
        );
    }

    /**
     * @param QueryBuilder $query
     */
    protected function customizeQuery(string $action, Request $request, $query): void
    {
        if ('_index' === $action) {
            $query->andWhere($query->expr()->eq('e.enabled', "'TRUE'"));
        }
    }

    protected function orderQuery(string $action, $query, Request $request, PaginatorInterface $paginator, $_format)
    {
        return $query->orderBy('e.label', 'ASC');
    }
}
