<?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\Services\MagicLinkService;

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

    #[CommandHandler]
    public function handle(GenerateMagicLinkCommand $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->toArray())) {
            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->magiclinkService->generate(
            action: $command->action,
            payload: $command->payload->toArray(),
            config: $config,
            createdByIp: $command->createdByIp,
            userAgent: $command->userAgent
        );

        // Build full URL
        $baseUrl = $command->baseUrl ?? '';

        return rtrim($baseUrl, '/') . '/magiclink/' . $token;
    }
}
