<?php

namespace App\Controller;

use App\ApiResource\MediaObjectApi;
use App\Entity\MediaObject;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Finder\Exception\AccessDeniedException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Attribute\AsController;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfonycasts\MicroMapper\MicroMapperInterface;
use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

#[AsController]
final class CreateMediaObjectAction extends AbstractController
{
    public function __construct(
        private MicroMapperInterface $microMapper,
        private EntityManagerInterface $em,
        private NormalizerInterface $normalizer
    ) {
    }

    public function __invoke(Request $request): JsonResponse
    {
        $uploadedFile = $request->files->get('file');
        if (!$uploadedFile) {
            throw new BadRequestHttpException('"file" is required');
        }

        // Sicherstellen dass ein User vorhanden ist
        $user = $this->getUser();
        if (!$user instanceof User) {
            throw new AccessDeniedException('User must be logged in');
        }

        $mediaObject = new MediaObject($user);
        $mediaObject->file = $uploadedFile;
        $this->em->persist($mediaObject);
        $this->em->flush();

        $mediaObjectApi = $this->microMapper->map($mediaObject, MediaObjectApi::class);

        // Normalisieren für jsonld Format (gibt die Metadaten)
        $normalized = $this->normalizer->normalize($mediaObjectApi, 'jsonld', ['groups' => 'media_object:read']);

        // Manuell die fehlenden Felder hinzufügen
        $normalized['dbId'] = $mediaObjectApi->dbId;
        $normalized['contentUrl'] = $mediaObjectApi->contentUrl;
        $normalized['filePath'] = $mediaObjectApi->filePath;
        $normalized['createdAt'] = $mediaObjectApi->createdAt->format('c');

        // In JSON umwandeln
        return new JsonResponse($normalized, 201);
    }
}