<?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\EventListener;

use Doctrine\Bundle\DoctrineBundle\Attribute\AsDoctrineListener;
use Doctrine\ORM\Event\PrePersistEventArgs;
use Doctrine\ORM\Events;
use Ferienpass\CoreBundle\Entity\TenantAwareInterface;
use Ferienpass\CoreBundle\Tenant\TenantContext;

/**
 * Stamps the active tenant onto every new tenant-aware row.
 *
 * Callers never have to think about `tenant_id`: the same
 * `new Offer(); $em->persist($offer);` that worked on a single-tenant build
 * lands in the right municipality on a shared one.
 *
 * A row written with no tenant active (a maintenance command, say) keeps a null
 * tenant. That is invisible to every tenant rather than visible to all of them,
 * which is the direction to fail in.
 */
#[AsDoctrineListener(event: Events::prePersist)]
class TenantPersistListener
{
    public function __construct(private readonly TenantContext $tenantContext)
    {
    }

    public function prePersist(PrePersistEventArgs $args): void
    {
        if (!$this->tenantContext->isEnabled()) {
            return;
        }

        $entity = $args->getObject();

        if (!$entity instanceof TenantAwareInterface || null !== $entity->getTenant()) {
            return;
        }

        $tenant = $this->tenantContext->getTenant();
        if (null === $tenant) {
            return;
        }

        $entity->setTenant($tenant);
    }
}
