<?php

declare(strict_types=1);

namespace App\Module\Core\Infrastructure\ApiPlatform\State\Processor;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Module\Core\Domain\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\SecurityBundle\Security;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

use function assert;

/**
 * Soft-delete processor wired on the User `Delete` operation: instead of
 * removing the row (which would orphan every task / time entry / notification
 * referencing it and break their serialization), the user is archived. The
 * account is kept for referential integrity but can no longer log in
 * (ArchivedUserChecker) and is hidden from selectable user lists
 * (ExcludeArchivedUserExtension).
 *
 * @implements ProcessorInterface<User, null|User>
 */
final readonly class UserArchiveProcessor implements ProcessorInterface
{
    public function __construct(
        private EntityManagerInterface $em,
        private Security $security,
    ) {}

    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): ?User
    {
        assert($data instanceof User);

        // Prevent an admin from archiving (locking out) their own account.
        $current = $this->security->getUser();
        if ($current instanceof User && $current->getId() === $data->getId()) {
            throw new AccessDeniedHttpException('You cannot archive your own account.');
        }

        if ($data->isArchived()) {
            return null;
        }

        $data->setArchived(true);
        $data->setApiToken(null);
        $this->em->flush();

        return null;
    }
}
