<?php

namespace App\Controller\Api;

use App\DTO\TaskRequest;
use App\Entity\Task;
use App\Enum\TaskStatus;
use App\Repository\TaskRepository;
use App\Service\TaskManager;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload as Payload;
use Symfony\Component\Routing\Attribute\Route;

#[Route('/api/tasks')]
class TaskController extends AbstractController
{
    public function __construct(
        private readonly TaskRepository $repo,
        private readonly TaskManager $manager,
    ) {
    }

    #[Route('', methods: ['GET'])]
    public function index(Request $req): JsonResponse
    {
        $tasks = match ($req->query->get('filter')) {
            'current' => $this->repo->currentTasks()->filterInactive()->sortByDueDate(),
            default => $this->repo->allTasks()->sortByDueDateDesc(),
        };

        return $this->json($tasks, 200, [], ['groups' => ['task:read']]);
    }

    #[Route('/statuses', methods: ['GET'])]
    public function statuses(): JsonResponse
    {
        return $this->json(TaskStatus::userSelectableValues());
    }

    #[Route('/{id}', methods: ['GET'], requirements: ['id' => '\d+'])]
    public function show(Task $task): JsonResponse
    {
        return $this->json($task, 200, [], ['groups' => ['task:read']]);
    }

    #[Route('/{id}', methods: ['PUT'], requirements: ['id' => '\d+'])]
    public function update(Task $task, #[Payload] TaskRequest $dto): JsonResponse
    {
        $task = $this->manager->update($task, $dto);

        return $this->json($task, 200, [], ['groups' => ['task:read']]);
    }

    #[Route('/{id}', methods: ['DELETE'], requirements: ['id' => '\d+'])]
    public function delete(Task $task): JsonResponse
    {
        $this->manager->delete($task);

        return new JsonResponse(null, 204);
    }

    #[Route('/{id}/toggle', methods: ['PATCH'], requirements: ['id' => '\d+'])]
    public function toggle(Task $task): JsonResponse
    {
        $task = $this->manager->toggle($task);

        return $this->json($task, 200, [], ['groups' => ['task:read']]);
    }
}
