<?php

namespace App\Repository;

use App\Entity\ActivityLog;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @extends ServiceEntityRepository<ActivityLog>
 */
class ActivityLogRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, ActivityLog::class);
    }

    /**
     * Page du journal, du plus récent au plus ancien, avec filtres optionnels.
     *
     * @return array{items: list<ActivityLog>, total: int}
     */
    public function search(?string $scanId, ?string $userEmail, ?string $action, int $page, int $perPage): array
    {
        $qb = $this->createQueryBuilder('l');
        if (null !== $scanId && '' !== $scanId) {
            $qb->andWhere('l.scanId = :scan')->setParameter('scan', $scanId);
        }
        if (null !== $userEmail && '' !== $userEmail) {
            $qb->andWhere('l.userEmail = :email')->setParameter('email', $userEmail);
        }
        if (null !== $action && '' !== $action) {
            $qb->andWhere('l.action = :action')->setParameter('action', $action);
        }

        $total = (int) (clone $qb)->select('COUNT(l.id)')->getQuery()->getSingleScalarResult();

        /** @var list<ActivityLog> $items */
        $items = $qb->orderBy('l.createdAt', 'DESC')
            ->addOrderBy('l.id', 'DESC')
            ->setFirstResult(max(0, $page - 1) * $perPage)
            ->setMaxResults($perPage)
            ->getQuery()
            ->getResult();

        return ['items' => $items, 'total' => $total];
    }

    /**
     * Auteurs distincts présents dans le journal (options du filtre).
     *
     * @return list<string>
     */
    public function distinctUsers(): array
    {
        /** @var list<string> $emails */
        $emails = $this->createQueryBuilder('l')
            ->select('DISTINCT l.userEmail')
            ->orderBy('l.userEmail', 'ASC')
            ->getQuery()
            ->getSingleColumnResult();

        return $emails;
    }

    /**
     * Dernières entrées pour un scan donné (affichage sur la page de détail).
     *
     * @return list<ActivityLog>
     */
    public function findRecentForScan(string $scanId, int $limit = 20): array
    {
        /** @var list<ActivityLog> $items */
        $items = $this->createQueryBuilder('l')
            ->andWhere('l.scanId = :scan')->setParameter('scan', $scanId)
            ->orderBy('l.createdAt', 'DESC')
            ->addOrderBy('l.id', 'DESC')
            ->setMaxResults($limit)
            ->getQuery()
            ->getResult();

        return $items;
    }
}
