<?php

namespace App\Controller;

use App\Entity\Messages;
use App\Entity\Supervision;
use App\Entity\User;
use App\Enums\MessageType;
use App\Libs\Libs;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Http\Attribute\CurrentUser;

class MessageController extends AbstractController
{
    public function __construct(
        private EntityManagerInterface $entityManager
    ) {
    }

    #[Route('/api/notifications/{msgId}', name: 'app_read_message')]
    public function readMessage(string $msgId): Response
    {
        /** @var Messages $message */
        $message = $this->entityManager->getRepository(Messages::class)->find($msgId);
        $message->setReceived(new \DateTimeImmutable());
        $this->entityManager->flush();

        return $this->json([
            'success' => true,
            'message' => 'Message marked as read',
            'link' => $message->getLink(),
        ]);
    }

    #[Route('/api/send-message', name: 'app_send_message')]
    public function sendMessage(Request $request, #[CurrentUser()] User $user): Response
    {
        $sup = $this->entityManager->getRepository(Supervision::class)->getSupervisorByWorker($user);
        $data = json_decode($request->getContent(), true);
        $message = new Messages();
        $message->setSender($user);
        $message->setSent(new \DateTimeImmutable());
        $message->setRecipient($sup);
        $message->setTitle('New Message');
        $message->setMessage($data['message']);
        $message->setType(MessageType::GENERAL);

        $this->entityManager->persist($message);
        $this->entityManager->flush();

        return $this->json([
            'success' => true,
            'message' => 'Message sent',
        ]);
    }
}
