<?php

declare(strict_types=1);

namespace App\Application\SmartLink\Api;

use App\Domain\SmartLink\Repositories\GeoRoutingRuleRepository;
use App\Domain\SmartLink\ValueObjects\SmartLinkId;
use App\Framework\Attributes\Route;
use App\Framework\Http\HttpRequest;
use App\Framework\Http\Method;
use App\Framework\Router\Result\JsonResult;

final readonly class GetGeoRoutingRules
{
    public function __construct(
        private GeoRoutingRuleRepository $geoRoutingRuleRepository
    ) {
    }

    #[Route(path: '/api/smartlinks/{linkId}/geo-rules', method: Method::GET)]
    public function __invoke(HttpRequest $request, string $linkId): JsonResult
    {
        $rules = $this->geoRoutingRuleRepository->findByLinkId(
            SmartLinkId::fromString($linkId)
        );

        $data = array_map(function ($rule) {
            return [
                'id' => $rule->id->toString(),
                'link_id' => $rule->linkId->toString(),
                'country_code' => $rule->countryCode->toString(),
                'destination_id' => $rule->destinationId,
                'priority' => $rule->priority,
                'created_at' => $rule->createdAt->format('Y-m-d H:i:s'),
            ];
        }, $rules);

        return new JsonResult(['rules' => $data]);
    }
}
