<?php

declare(strict_types=1);

namespace App\Application\SmartLink;

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

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

    #[Route(path: '/s/{shortCode}', method: Method::GET)]
    public function __invoke(HttpRequest $request): Redirect
    {
        $shortCode = ShortCode::fromString($request->routeParameters->get('shortCode'));
        $ip = IpAddress::fromString($request->server->getClientIp());
        $userAgent = $request->server->getUserAgent();

        // Resolve destination URL
        $destinationUrl = $this->routingEngine->resolveDestination(
            shortCode: $shortCode,
            ip: $ip,
            userAgent: $userAgent
        );

        // Track click
        $link = $this->routingEngine->linkService->findByShortCode($shortCode);
        if ($link->settings->trackClicks) {
            $this->trackingService->trackClick(
                linkId: $link->id,
                ip: $ip,
                userAgent: $userAgent,
                referer: $request->server->getSafeRefererUrl(),
                destinationService: null // TODO: Extract from destinationUrl
            );
        }

        return new Redirect($destinationUrl->toString());
    }
}
