<?php

namespace App\Auth\Repository;

use App\Auth\Entity\User;
use App\Auth\Entity\UserActiveContext;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

class UserActiveContextRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, UserActiveContext::class);
    }

    public function findByUser(User $user): ?UserActiveContext
    {
        return $this->findOneBy(['user' => $user]);
    }

    public function upsert(User $user, string $dbUuid): UserActiveContext
    {
        $ctx = $this->findByUser($user);
        if ($ctx === null) {
            $ctx = new UserActiveContext($user, $dbUuid);
            $this->getEntityManager()->persist($ctx);
        } else {
            $ctx->setDbUuid($dbUuid);
        }
        $this->getEntityManager()->flush();
        return $ctx;
    }
}
