<?php

declare(strict_types=1);

namespace App\Domain\SmartLink\Services;

use App\Domain\SmartLink\Entities\ClickEvent;
use App\Domain\SmartLink\Entities\SmartLink;
use App\Domain\SmartLink\Enums\ServiceType;
use App\Domain\SmartLink\Repositories\ClickEventRepository;
use App\Domain\SmartLink\ValueObjects\SmartLinkId;
use App\Framework\DateTime\Clock;
use App\Framework\Http\HttpRequest;
use App\Infrastructure\GeoIp\GeoIp;

final readonly class ClickTrackingService
{
    public function __construct(
        private ClickEventRepository $repository,
        private GeoIp $geoIp,
        private Clock $clock
    ) {
    }

    public function trackClick(
        SmartLink $smartLink,
        HttpRequest $request,
        ServiceType $destinationService
    ): ClickEvent {
        $ip = $request->server->getClientIp();
        $userAgent = $request->server->getUserAgent();
        $referer = $request->server->getReferer();
        $countryCode = $this->geoIp->getCountryCode($ip);

        $event = ClickEvent::create(
            clock: $this->clock,
            linkId: $smartLink->id,
            ip: $ip,
            countryCode: $countryCode,
            userAgent: $userAgent,
            referer: $referer,
            destinationService: $destinationService->value
        );

        $this->repository->save($event);

        return $event;
    }

    public function isUniqueClick(ClickEvent $event): bool
    {
        $recentClicks = $this->repository->getRecentClicksByIpHash($event->ipHash, 60);

        return $event->isUnique($recentClicks);
    }

    public function getLinkStats(SmartLinkId $linkId): array
    {
        return [
            'total_clicks' => $this->repository->countByLinkId($linkId),
            'unique_clicks' => $this->repository->countUniqueByLinkId($linkId),
            'conversions' => $this->repository->getConversionsByLinkId($linkId),
        ];
    }
}
