<?php

namespace App\Framework\Smartlinks\Commands;

use App\Framework\CommandBus\CommandHandler;
use App\Framework\Smartlinks\Actions\ActionRegistry;
use App\Framework\Smartlinks\Services\SmartlinkService;

final readonly class GenerateSmartlinkHandler
{
    public function __construct(
        private SmartlinkService $smartlinkService,
        private ActionRegistry $actionRegistry
    ) {}

    #[CommandHandler]
    public function handle(GenerateSmartlinkCommand $command): string
    {
        // Validate action exists
        $action = $this->actionRegistry->get($command->action);
        if (!$action) {
            throw new \InvalidArgumentException("Unknown action: {$command->action}");
        }

        // Validate payload
        if (!$action->validatePayload($command->payload)) {
            throw new \InvalidArgumentException("Invalid payload for action: {$command->action}");
        }

        // Use action's default config if none provided
        $config = $command->config ?? $action->getDefaultConfig();

        // Generate token
        $token = $this->smartlinkService->generate(
            action: $command->action,
            payload: $command->payload,
            config: $config,
            createdByIp: $command->createdByIp,
            userAgent: $command->userAgent
        );

        // Build full URL
        $baseUrl = $command->baseUrl ?? '';
        return rtrim($baseUrl, '/') . '/smartlink/' . $token;
    }
}
