<?php

declare(strict_types=1);

namespace App\Application\SmartLink\Api;

use App\Domain\SmartLink\Services\ClickTrackingService;
use App\Domain\SmartLink\Services\LinkRoutingEngine;
use App\Domain\SmartLink\Services\SmartLinkService;
use App\Domain\SmartLink\ValueObjects\ShortCode;
use App\Framework\Attributes\Route;
use App\Framework\Http\HttpRequest;
use App\Framework\Http\Method;
use App\Framework\Router\Result\Redirect;

final readonly class RedirectToDestination
{
    public function __construct(
        private SmartLinkService $smartLinkService,
        private LinkRoutingEngine $routingEngine,
        private ClickTrackingService $trackingService
    ) {
    }

    #[Route(path: '/l/{shortCode}', method: Method::GET)]
    public function __invoke(HttpRequest $request, string $shortCode): Redirect
    {
        $smartLink = $this->smartLinkService->getLinkByShortCode(
            ShortCode::fromString($shortCode)
        );

        $destination = $this->routingEngine->resolveDestination(
            smartLink: $smartLink,
            request: $request
        );

        $this->trackingService->trackClick(
            smartLink: $smartLink,
            request: $request,
            destinationService: $destination->serviceType
        );

        return new Redirect($destination->url->toString());
    }
}
