<?php

namespace App\Mapper;

use App\ApiResource\UserZoneApi;
use App\Entity\UserZone;
use App\Repository\UserRepository;
use App\Repository\UserZoneRepository;
use App\Repository\ZoneRepository;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;

#[AsMapper(from: UserZoneApi::class, to: UserZone::class)]
class UserZoneApiToEntityMapper implements MapperInterface
{
    public function __construct(
        private readonly UserZoneRepository $userZoneRepository,
        private readonly UserRepository $userRepository,
        private readonly ZoneRepository $zoneRepository
    ) {}

    public function load(object $from, string $toClass, array $context): object
    {
        $dto = $from;
        assert($dto instanceof UserZoneApi);

        $entity = $dto->id ? $this->userZoneRepository->find($dto->id) : new UserZone();
        if ($dto->id && !$entity) {
            throw new \Exception('UserZone not found');
        }

        return $entity;
    }

    public function populate(object $from, object $to, array $context): object
    {
        assert($from instanceof UserZoneApi);
        assert($to instanceof UserZone);

        if ($from->userIri) {
            $user = $this->userRepository->find($from->userIri->id);
            if (!$user) {
                throw new \Exception('User not found');
            }
            $to->setUser($user);
        }

        if ($from->zoneIri) {
            $zone = $this->zoneRepository->find($from->zoneIri->id);
            if (!$zone) {
                throw new \Exception('Zone not found');
            }
            $to->setZone($zone);
        }

        return $to;
    }
}
