<?php

declare(strict_types=1);

namespace App\Framework\MagicLinks\Commands;

use App\Framework\CommandBus\CommandHandler;
use App\Framework\MagicLinks\Actions\ActionRegistry;
use App\Framework\MagicLinks\Actions\ActionResult;
use App\Framework\MagicLinks\Services\MagicLinkService;

final readonly class ExecuteMagicLinkHandler
{
    public function __construct(
        private MagicLinkService $magiclinkService,
        private ActionRegistry $actionRegistry
    ) {
    }

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

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

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

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

        return $result;
    }
}
