<?php

namespace App\Controller;

use App\Entity\Message;
use App\Entity\UserApp;
use App\Form\MessageType;
use App\Repository\AnnouncementRepository;
use App\Repository\InternSkillRepository;
use App\Repository\MessageRepository;
use App\Repository\UserRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\Routing\Attribute\Route;

#[Route('/message')]
final class MessageController extends AbstractController
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private readonly MessageRepository $messageRepository,
        private readonly UserRepository $userRepository,
    ){}
    #[Route(name: 'app_message_index', methods: ['GET'])]
    public function index(): Response
    {
        $user = $this->getUser();
        if (!$user instanceof UserApp) {
            throw new AccessDeniedHttpException("erreur");
        }
        $messages = $this->messageRepository->findLatestMessagesByUser($user);

        return $this->render('message/index.html.twig', [
            'messages' => $messages,
        ]);
    }

    #[Route('/conversation/{id}', name: 'app_message_conversation', methods: ['GET'])]
    public function conversation(Message $message,): Response
    {
        $user = $this->getUser();
        $otherUser = $message->getSender() === $user ? $message->getReceiver() : $message->getSender();

        $conversation = $this->messageRepository->findByConversation($user, $otherUser);

        return $this->render('message/conversation.html.twig', [
            'conversation' => $conversation,
            'receiverId' => $otherUser->getId(),
            'receiver' => $otherUser,
        ]);
    }


    #[Route('/new/{receiverId}', name: 'app_message_new', methods: ['GET', 'POST'])]
    public function new(Request $request, ?int $receiverId = null,): Response
    {
        $message = new Message();

        if ($receiverId) {
            $receiver = $this->userRepository->find($receiverId);
            if ($receiver) {
                $message->setReceiver($receiver);
            }
        }

        $form = $this->createForm(MessageType::class, $message);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $message->setSendingDate(new \DateTime());
            $message->setSender($this->getUser());

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

            return $this->redirectToRoute('app_message_index');
        }

        return $this->render('message/new.html.twig', [
            'form' => $form,
        ]);
    }

    #[Route('/{id}', name: 'app_message_show', methods: ['GET'])]
    public function show(Message $message): Response
    {
        return $this->render('message/show.html.twig', [
            'message' => $message,
        ]);
    }

    #[Route('/{id}/edit', name: 'app_message_edit', methods: ['GET', 'POST'])]
    public function edit(Request $request, Message $message,): Response
    {
        $form = $this->createForm(MessageType::class, $message);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $message->setSendingDate(new \DateTime());
            $this->entityManager->flush();

            return $this->redirectToRoute('app_message_index', [], Response::HTTP_SEE_OTHER);
        }

        return $this->render('message/edit.html.twig', [
            'message' => $message,
            'form' => $form,
        ]);
    }

    #[Route('/{id}', name: 'app_message_delete', methods: ['POST'])]
    public function delete(Request $request, Message $message,): Response
    {
        if ($this->isCsrfTokenValid('delete'.$message->getId(), $request->getPayload()->getString('_token'))) {
            $this->entityManager->remove($message);
            $this->entityManager->flush();
        }

        return $this->redirectToRoute('app_message_index', [], Response::HTTP_SEE_OTHER);
    }


}
