<?php

declare(strict_types=1);

namespace App\Controller;

use Doctrine\DBAL\Connection;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[AsController]
final class CustomFieldNamesController
{
    public function __construct(private readonly Connection $connection) {}

    #[Route(
        path: '/api/custom-fields/names',
        name: 'api_custom_fields_names',
        methods: ['GET']
    )]
    #[IsGranted('ROLE_VIEWER')]
    public function __invoke(): JsonResponse
    {
        $sql = <<<'SQL'
                SELECT DISTINCT name
                FROM custom_fields
                WHERE name IS NOT NULL AND name <> ''
                ORDER BY name ASC
            SQL;

        $names = $this->connection->fetchFirstColumn($sql);

        return new JsonResponse($names);
    }
}
