<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\Repository;

use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Ferienpass\CoreBundle\Entity\User;
use Ferienpass\CoreBundle\Entity\Wishlist;
use Symfony\Component\Uid\Uuid;

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

    /**
     * Active (non-tombstoned) wishlists of a user.
     *
     * @return Wishlist[]
     */
    public function findActiveForUser(User $user): array
    {
        return $this->createQueryBuilder('w')
            ->where('w.user = :user')
            ->andWhere('w.deletedAt IS NULL')
            ->setParameter('user', $user)
            ->orderBy('w.createdAt', 'ASC')
            ->getQuery()
            ->getResult()
        ;
    }

    /**
     * A user's wishlist by its client-generated (localStorage) uuid, regardless
     * of tombstone state (the reconcile needs to revive or re-delete an
     * existing row rather than create a duplicate).
     */
    public function findOneForUserByClientUuid(User $user, Uuid $clientUuid): ?Wishlist
    {
        return $this->findOneBy(['user' => $user, 'clientUuid' => $clientUuid]);
    }

    /**
     * Client uuids of a user's tombstoned wishlists — returned to clients so
     * other devices drop them from localStorage. Returned in the same rfc4122
     * form the client generates (crypto.randomUUID), not base58 (the offer ref
     * format). Lists without a client uuid (server-origin) are skipped.
     *
     * @return string[] rfc4122 client uuids
     */
    public function findDeletedClientUuidsForUser(User $user): array
    {
        $rows = $this->createQueryBuilder('w')
            ->select('w.clientUuid')
            ->where('w.user = :user')
            ->andWhere('w.deletedAt IS NOT NULL')
            ->andWhere('w.clientUuid IS NOT NULL')
            ->setParameter('user', $user)
            ->getQuery()
            ->getResult()
        ;

        return array_map(static function (array $r): string {
            $uuid = $r['clientUuid'];

            return $uuid instanceof Uuid ? $uuid->toRfc4122() : Uuid::fromString((string) $uuid)->toRfc4122();
        }, $rows);
    }
}
