<?php

namespace App\Repository;

use App\Entity\Device;
use App\Entity\Family;
use App\Enum\DeviceStatus;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

final class DeviceRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Device::class);
    }

    public function findUsableByCredentialDigest(string $digest, \DateTimeImmutable $now): ?Device
    {
        return $this->createQueryBuilder('device')
            ->andWhere('device.credentialDigest = :digest')
            ->andWhere('device.status = :status')
            ->andWhere('device.credentialExpiresAt > :now')
            ->setParameter('digest', $digest)
            ->setParameter('status', DeviceStatus::Active)
            ->setParameter('now', $now)
            ->getQuery()
            ->getOneOrNullResult();
    }

    public function findPendingByPairingDigest(string $digest): ?Device
    {
        return $this->createQueryBuilder('device')
            ->andWhere('device.pairingCodeDigest = :digest')
            ->andWhere('device.status = :status')
            ->setParameter('digest', $digest)
            ->setParameter('status', DeviceStatus::Pending)
            ->getQuery()
            ->getOneOrNullResult();
    }

    /** @return list<Device> */
    public function findForFamily(Family $family): array
    {
        return $this->findBy(['family' => $family], ['createdAt' => 'DESC']);
    }

    public function findOneForFamily(int $id, Family $family): ?Device
    {
        return $this->findOneBy(['id' => $id, 'family' => $family]);
    }
}
