<?php

namespace App\Mapper;

use App\ApiResource\UserApi;
use App\Entity\User;
use App\Repository\MediaObjectRepository;
use App\Repository\UserRepository;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;

#[AsMapper(from: UserApi::class, to: User::class)]
class UserApiToEntityMapper implements MapperInterface
{
    public function __construct(
        private UserRepository              $repository,
        private UserPasswordHasherInterface $userPasswordHasher,
        private MediaObjectRepository $mediaObjectRepository,
    )
    {
    }

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

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

        return $entity;
    }

    public function populate(object $from, object $to, array $context): object
    {
        $dto = $from;
        assert($dto instanceof UserApi);
        $entity = $to;
        assert($entity instanceof User);

        $entity->setEmail($dto->email);
        $entity->setReferenceId($dto->referenceId);
        $entity->setFirstName($dto->firstName);
        $entity->setLastName($dto->lastName);
        $entity->setActive($dto->active);
        $entity->setIsPilot($dto->isPilot);

        $roles = $entity->getRoles();
        if ($dto->isAdmin && !in_array(User::ROLE_ADMIN, $roles, true)) {
            $entity->setRoles([User::ROLE_ADMIN, User::ROLE_USER]);
        }

        if (!$dto->isAdmin && in_array(User::ROLE_ADMIN, $roles, true)) {
            $entity->setRoles([User::ROLE_USER]);
        }

        if ($dto->password) {
            $entity->setPassword($this->userPasswordHasher->hashPassword($entity, $dto->password));
        }

        if ($dto->imageIri) {
            $image = $this->mediaObjectRepository->find($dto->imageIri->id);
            if (!$image) {
                throw new \Exception('Image not found');
            }
            $entity->setImage($image);
        } else {
            $entity->setImage(null);
        }

        return $entity;
    }
}
