<?php

declare(strict_types=1);

namespace App\State\Provider\Shop;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProviderInterface;
use App\Entity\Shop\ShopRequest;
use App\Enum\Shop\ShopRequestStatus;
use App\Service\Shop\ShopService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;

/**
 * Provider for NewStructureTrialRequest validation.
 */
final class ShopRequestProvider implements ProviderInterface
{
    public function __construct(
        private readonly EntityManagerInterface $entityManager,
        private readonly ShopService $shopService,
    ) {
    }

    /**
     * @param array<mixed> $uriVariables
     * @param array<mixed> $context
     */
    public function provide(Operation $operation, array $uriVariables = [], array $context = []): Response
    {
        // Find the request by token
        $token = $uriVariables['token'] ?? null;

        if (!$token) {
            throw new NotFoundHttpException('Token not provided');
        }

        $repository = $this->entityManager->getRepository(ShopRequest::class);
        $shopRequest = $repository->findOneBy(['token' => $token]);

        if (!$shopRequest) {
            throw new NotFoundHttpException('Request not found or already validated');
        }

        if ($shopRequest->getStatus() !== ShopRequestStatus::ACTIVATION_LINK_SENT) {
            throw new AccessDeniedHttpException('Invalid request status');
        }

        // Check if the submission date is more than 15 minutes old
        $now = new \DateTimeImmutable();
        $requestAge = $now->getTimestamp() - $shopRequest->getSubmissionDate()->getTimestamp();

        if ($requestAge >= 15 * 60) {
            throw new AccessDeniedHttpException('Request expired: submission date is more than 15 minutes old');
        }

        // Validate the request using the ShopService
        $this->shopService->processShopRequest($shopRequest);

        // Return a success response
        // TODO: redirect to a confirmation page
        return new Response('Request validated successfully', Response::HTTP_OK);
    }

}
