<?php

declare(strict_types=1);

namespace App\Application\SmartLink;

use App\Domain\SmartLink\Entities\LinkDestination;
use App\Domain\SmartLink\Enums\ServiceType;
use App\Domain\SmartLink\Services\SmartLinkService;
use App\Domain\SmartLink\ValueObjects\DestinationUrl;
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 AddLinkDestination
{
    public function __construct(
        private SmartLinkService $linkService
    ) {
    }

    #[Route(path: '/api/smart-links/{id}/destinations', method: Method::POST)]
    public function __invoke(HttpRequest $request): JsonResult
    {
        $linkId = SmartLinkId::fromString($request->routeParameters->get('id'));
        $data = $request->parsedBody->toArray();

        $destination = LinkDestination::create(
            linkId: $linkId,
            serviceType: ServiceType::from($data['service_type']),
            url: DestinationUrl::fromString($data['url']),
            priority: (int) ($data['priority'] ?? 0),
            isDefault: (bool) ($data['is_default'] ?? false)
        );

        $this->linkService->addDestination($linkId, $destination);

        return new JsonResult([
            'message' => 'Destination added successfully',
            'destination' => $destination->toArray(),
        ], 201);
    }
}
