<?php

namespace App\Controller;

use App\Entity\Building;
use App\Entity\Project;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\CurrentUser;

final class ProjectController extends AbstractController
{
    #[Route('/project', name: 'app_project')]
    public function index(): Response
    {
        return $this->render('project/index.html.twig', [
            'controller_name' => 'ProjectController',
        ]);
    }

    #[Route('/projects', name: 'app_projects')]
    public function projects(#[CurrentUser] User $user, EntityManagerInterface $em): Response
    {
        $repo = $em->getRepository(Project::class);
        $projects = $repo->findBy(['user' => $user]);

        return $this->render('project/index.html.twig', [
            'controller_name' => 'ProjectController',
            'projects' => $projects,
        ]);
    }

    #[Route('/project/create', name: 'app_project_create', methods: ['POST'])]
    public function create(
        EntityManagerInterface $em,
        Request $request,
        #[CurrentUser()]
        User $user
        ): JsonResponse
    {
        $data = $request->getPayload();
        $datetime = new \DateTimeImmutable();

        $building = new Building();
        $building->setName($data->get('name'));
        $em->persist($building);
        $em->flush();

        $project = new Project();
        $project->setUser($user);
        $project->setBuilding($building);
        $project->setIfc($data->get('ifc'));
        $project->setCreatedAt($datetime);
        $project->setLastModified($datetime);
        $em->persist($project);
        $em->flush();

        $user->addProject($project);

        // TODO Does the JSON Building object include its ID?
        return $this->json([
            'id' => $building->getId(),
            'name' => $building->getName()]
        );
    }
}
