<?php

namespace App\Repository;

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

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

    /**
     * Trouve une clé API valide par token
     */
    public function findValidByToken(string $token): ?ApiKey
    {
        $apiKey = $this->findOneBy(['token' => $token]);

        if (!$apiKey || !$apiKey->isValid()) {
            return null;
        }

        return $apiKey;
    }

    /**
     * Trouve toutes les clés API d'un utilisateur
     */
    public function findByUser($user): array
    {
        return $this->findBy(['user' => $user], ['createdAt' => 'DESC']);
    }

    /**
     * Supprime les clés API expirées
     */
    public function deleteExpiredKeys(): int
    {
        return $this->createQueryBuilder('ak')
            ->delete()
            ->where('ak.expiresAt < :now')
            ->setParameter('now', new \DateTime())
            ->getQuery()
            ->execute();
    }
}

