<?php

declare(strict_types=1);

namespace App\Controller\Api;

use App\Service\Prices\RedisReadService;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Throwable;

final class PricesController extends AbstractController
{
    public function __construct(
        private readonly RequestStack $requestStack,
        private readonly RedisReadService $readService
    ) {}

    #[Route('/api/prices/{type}', name: 'api_prices_get', methods: ['GET'], utf8: true)]
    public function indexGet(string $type = ''): JsonResponse
    {
        return new JsonResponse([
            'status' => Response::HTTP_METHOD_NOT_ALLOWED,
            'error' => 'This endpoint only accepts POST requests. Please use POST with a JSON payload.',
        ], Response::HTTP_METHOD_NOT_ALLOWED);
    }

    #[Route('/api/prices/{type}', name: 'api_prices_post', methods: ['POST'], utf8: true)]
    public function indexPost(string $type = ''): JsonResponse
    {
        $request = $this->requestStack->getCurrentRequest();

        try {
            $params = json_decode($request->getContent(), true, 512, JSON_THROW_ON_ERROR);
        } catch (Throwable $e) {
            return new JsonResponse(['error' => 'Invalid JSON'], Response::HTTP_BAD_REQUEST);
        }

        return $this->handleRequest($type, $params);
    }

    private function handleRequest(string $type, array $params): JsonResponse
    {
        $callType = $type ?: RedisReadService::RAW_DATA;

        try {
            $result = $this->readService->getPricesForSkus($params, $callType);
            return new JsonResponse($result);
        } catch (Throwable $e) {
            return new JsonResponse(['error' => $e->getMessage()], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
    }
}
