<?php

namespace App\Handler;

use App\Entity\OrganizationalUnit;
use App\Repository\ClientRepository;
use App\Repository\OrganizationalUnitRepository;

readonly class OrganizationalUnitChangeParentHandler
{
    public function __construct(
        private OrganizationalUnitRepository $organizationalUnitRepository,
        private ClientRepository             $clientRepository
    )
    {
    }

    public function handle(OrganizationalUnit $organizationalUnit): OrganizationalUnit
    {
        $parent = $organizationalUnit->getParent();

        if (!$parent) {
            return throw new \InvalidArgumentException('The organizational unit has no parent.');
        }

        foreach ($organizationalUnit->getClients() as $client) {
            $client->setOrganizationalUnit($parent);
            $this->clientRepository->save($client);
        }

        $this->organizationalUnitRepository->delete($organizationalUnit);

        return $organizationalUnit;
    }
}