<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Contracts\HttpClient\HttpClientInterface;

class SonarBadgeController extends AbstractController
{
    private const ALLOWED_METRICS = [
        'alert_status',
        'security_rating',
        'reliability_rating',
        'sqale_rating',
        'coverage',
        'vulnerabilities',
        'bugs',
        'code_smells',
    ];

    #[Route('/badge/sonar/{metric}.svg', name: 'app_sonar_badge', requirements: ['metric' => '[a-z_]+'])]
    public function badge(
        string $metric,
        HttpClientInterface $httpClient,
        #[Autowire(env: 'SONARQUBE_URL')] string $sonarUrl,
        #[Autowire(env: 'SONARQUBE_BADGE_TOKEN')] string $sonarToken,
        #[Autowire(env: 'SONARQUBE_PROJECT_KEY')] string $projectKey,
    ): Response {
        if (!\in_array($metric, self::ALLOWED_METRICS, true)) {
            return new Response('', 404);
        }

        $url = sprintf(
            '%s/api/project_badges/measure?project=%s&metric=%s&token=%s',
            $sonarUrl,
            $projectKey,
            $metric,
            $sonarToken,
        );

        $response = $httpClient->request('GET', $url);
        $svg = $response->getContent(false);

        return new Response($svg, 200, [
            'Content-Type' => 'image/svg+xml',
            'Cache-Control' => 'public, max-age=300',
        ]);
    }
}
