<?php

namespace App\Controller;

use App\Entity\ActivityLog;
use App\Repository\ActivityLogRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

/**
 * Journal d'audit (ADMIN + AUDIT) : qui a validé/rouvert un scan, modifié ses
 * concessions, importé un référentiel, géré un utilisateur, etc.
 */
#[IsGranted('ROLE_AUDIT')]
final class JournalController extends AbstractController
{
    private const PER_PAGE = 50;

    #[Route('/journal', name: 'app_journal', methods: ['GET'])]
    public function index(Request $request, ActivityLogRepository $logs): Response
    {
        $page = max(1, $request->query->getInt('page', 1));
        $scanId = $request->query->getString('scan');
        $userEmail = $request->query->getString('user');
        $action = $request->query->getString('action');
        if ('' !== $action && !isset(ActivityLog::LABELS[$action])) {
            $action = '';
        }

        $result = $logs->search($scanId ?: null, $userEmail ?: null, $action ?: null, $page, self::PER_PAGE);

        return $this->render('page/journal.html.twig', [
            'items' => $result['items'],
            'total' => $result['total'],
            'page' => $page,
            'pages' => max(1, (int) ceil($result['total'] / self::PER_PAGE)),
            'users' => $logs->distinctUsers(),
            'actionLabels' => ActivityLog::LABELS,
            'filters' => ['scan' => $scanId, 'user' => $userEmail, 'action' => $action],
        ]);
    }
}
