<?php

namespace App\Mapper;

use App\ApiResource\MediaObjectApi;
use App\ApiResource\UserApi;
use App\Entity\User;
use App\Service\FileUrlService;
use Symfonycasts\MicroMapper\AsMapper;
use Symfonycasts\MicroMapper\MapperInterface;
use Symfonycasts\MicroMapper\MicroMapperInterface;

#[AsMapper(from: User::class, to: UserApi::class)]
class UserEntityToApiMapper implements MapperInterface
{
    public function __construct(
        private MicroMapperInterface $microMapper,
        private FileUrlService $fileUrlService
    )
    {
    }

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

        $dto = new UserApi();
        $dto->id = $entity->getId();

        return $dto;
    }

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

        $dto->dbId = $entity->getId();
        $dto->email = $entity->getEmail();
        $dto->referenceId = $entity->getReferenceId();
        $dto->firstName = $entity->getFirstName();
        $dto->lastName = $entity->getLastName();
        $dto->roles = $entity->getRoles();
        $dto->isAdmin = in_array(User::ROLE_ADMIN, $entity->getRoles(), true);
        $dto->active = $entity->isActive();
        $dto->isPilot = $entity->isPilot();

        $dto->imageIri = $dto->image = null;
        if ($entity->getImage() !== null) {
            $dto->imageIri = $dto->image = $this->microMapper->map($entity->getImage(), MediaObjectApi::class, [
                MicroMapperInterface::MAX_DEPTH => 5,
            ]);
        }

        $dto->imageUrl = $this->fileUrlService->getFileUrl($entity->getImage());
        $dto->fullName = $entity->getFirstName() . " " . $entity->getLastName();
        $dto->createdAt = $entity->getCreatedAt();

        return $dto;
    }
}
