<?php

declare(strict_types=1);

namespace App\Framework\MagicLinks\Actions;

use App\Framework\Http\ValueObjects\IpPatternCollection;
use App\Framework\MagicLinks\MagicLinkData;
use App\Framework\MagicLinks\TokenConfig;
use App\Framework\MagicLinks\ValueObjects\ActionResultData;
use App\Framework\MagicLinks\ValueObjects\Metadata;

final readonly class PasswordResetAction implements MagicLinkAction
{
    public function getName(): string
    {
        return 'password_reset';
    }

    public function getDefaultConfig(): TokenConfig
    {
        return new TokenConfig(
            expiryHours: 1, // Short expiry for security
            oneTimeUse: true,
            maxUses: 1,
            requireSecureContext: true,
            allowedIpRanges: IpPatternCollection::empty(),
            metadata: Metadata::empty()
        );
    }

    public function validatePayload(array $payload): bool
    {
        return ! empty($payload['user_id']) &&
            ! empty($payload['email']) &&
            filter_var($payload['email'], FILTER_VALIDATE_EMAIL);
    }

    public function execute(MagicLinkData $magiclinkData, array $context = []): ActionResult
    {
        $payload = $magiclinkData->payload;

        // Password reset form would be shown here
        // Return data needed for the password reset form

        return ActionResult::success(
            message: "Password reset form ready",
            data: ActionResultData::fromArray([
                'user_id' => $payload->get('user_id'),
                'email' => $payload->get('email'),
                'form_action' => '/password/reset/submit',
                'csrf_token' => $context['csrf_token'] ?? null,
            ])
        );
    }

    public function getRequiredPermissions(): array
    {
        return [];
    }
}
