<?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 METRICS = [
        'coverage', 'duplicated_lines_density', 'ncloc', 'alert_status',
        'security_hotspots', 'software_quality_reliability_issues',
        'software_quality_maintainability_issues', 'software_quality_security_issues',
        'software_quality_maintainability_rating', 'software_quality_reliability_rating',
        'software_quality_security_rating', 'software_quality_maintainability_remediation_effort',
    ];

    #[Route('/badge/sonar/{metric}.svg', name: 'app_sonar_badge', methods: ['GET'])]
    public function badge(
        string $metric,
        HttpClientInterface $httpClient,
        #[Autowire(env: 'SONARQUBE_URL')] string $sonarUrl,
        #[Autowire(env: 'SONARQUBE_PROJECT_KEY')] string $projectKey,
        #[Autowire(env: 'SONARQUBE_BADGE_TOKEN')] string $badgeToken,
    ): Response {
        if (!\in_array($metric, self::METRICS, true)) {
            return new Response('', Response::HTTP_NOT_FOUND);
        }

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

        $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',
        ]);
    }
}
