<?php

namespace App\Framework\Smartlinks\Commands;

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

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

    #[CommandHandler]
    public function handle(ExecuteSmartlinkCommand $command): ActionResult
    {
        // Validate token
        $smartlinkData = $this->smartlinkService->validate($command->token);
        if (!$smartlinkData) {
            return ActionResult::failure('Invalid or expired smartlink');
        }

        // Get action
        $action = $this->actionRegistry->get($smartlinkData->action);
        if (!$action) {
            return ActionResult::failure('Unknown action: ' . $smartlinkData->action);
        }

        // Execute action
        $result = $action->execute($smartlinkData, $command->context);

        // Mark as used if one-time use
        if ($smartlinkData->oneTimeUse && $result->isSuccess()) {
            $this->smartlinkService->markAsUsed($command->token);
        }

        return $result;
    }
}
