<?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 DocumentAccessAction implements MagicLinkAction
{
    public function getName(): string
    {
        return 'document_access';
    }

    public function getDefaultConfig(): TokenConfig
    {
        return new TokenConfig(
            expiryHours: 72, // 3 days
            oneTimeUse: false, // Can be accessed multiple times
            maxUses: 10,
            requireSecureContext: false,
            allowedIpRanges: IpPatternCollection::empty(),
            metadata: Metadata::empty()
        );
    }

    public function validatePayload(array $payload): bool
    {
        return ! empty($payload['document_id']) &&
            in_array($payload['access_level'], ['read', 'download', 'edit']);
    }

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

        // Document access logic
        return ActionResult::success(
            message: "Document access granted",
            data: ActionResultData::fromArray([
                'document_id' => $payload->get('document_id'),
                'access_level' => $payload->get('access_level'),
                'download_url' => "/documents/{$payload->get('document_id')}/download",
                'expires_at' => $magiclinkData->expiresAt->format('Y-m-d H:i:s'),
            ])
        );
    }

    public function getRequiredPermissions(): array
    {
        return ['documents.access'];
    }
}
