<?php

declare(strict_types=1);

namespace App\Controller;

use App\Payload\SignalPayload;
use App\Service\ClientKeyProvider;
use App\Service\SignalSnapshotService;
use App\Service\SignalSubmissionService;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Attribute\MapQueryParameter;
use Symfony\Component\HttpKernel\Attribute\MapRequestPayload;
use Symfony\Component\Routing\Annotation\Route;

#[Route(path: '/api/signals')]
class SignalController
{
    public function __construct(
        private readonly SignalSnapshotService $snapshotService,
        private readonly SignalSubmissionService $submissionService,
        private readonly ClientKeyProvider $clientKeyProvider,
    ) {
    }

    #[Route(path: '', name: 'api_signals_index', methods: ['GET'])]
    public function index(Request $request, #[MapQueryParameter('limit', flags: FILTER_NULL_ON_FAILURE)] ?int $limit = null): JsonResponse
    {
        $clientKey = $this->clientKeyProvider->fromRequest($request);
        $snapshot = $this->snapshotService->buildSnapshot($limit, $clientKey);

        return new JsonResponse($snapshot);
    }

    #[Route(path: '', name: 'api_signals_store', methods: ['POST'])]
    public function store(Request $request, #[MapRequestPayload] SignalPayload $payload): JsonResponse
    {
        $clientKey = $this->clientKeyProvider->fromRequest($request);
        $signal = $this->submissionService->submit($clientKey, $payload);

        return new JsonResponse([
            'status' => 'stored',
            'clientKey' => $clientKey,
            'point' => [
                'id' => $signal->id->toString(),
                'signalLocation' => [
                    'lat' => $signal->signalLocation->getLat(),
                    'lng' => $signal->signalLocation->getLng(),
                ],
                'createdAt' => $signal->createdAt->format(DATE_ATOM),
                'userKey' => $signal->userKey,
            ],
        ], Response::HTTP_CREATED);
    }
}
