<?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, string $dbType): UserActiveContext
    {
        $ctx = $this->findByUser($user);
        if ($ctx === null) {
            $ctx = new UserActiveContext($user, $dbUuid, $dbType);
            $this->getEntityManager()->persist($ctx);
        } else {
            $ctx->setContext($dbUuid, $dbType);
        }
        $this->getEntityManager()->flush();
        return $ctx;
    }
}
